[Leetcode][JAVA] Minimum Depth of Binary Tree && Balanced Binary Tree

來源:互聯網
上載者:User

標籤:

Minimum Depth of Binary Tree

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

 比較左子樹和右子樹的深度,取小的那個返回上來,並+1。

 需要注意的是如果沒有左子樹或右子樹。那麼無條件取存在的那一邊子樹深度,並+1.

如果左子樹和右子樹都沒有,那麼就是葉子節點,返回深度1.

如果root自身為null,返回0

 1 public int minDepth(TreeNode root) { 2         if(root==null) 3             return 0; 4         if(root.left==null && root.right==null) 5             return 1; 6         if(root.right==null) 7             return minDepth(root.left)+1; 8         if(root.left==null) 9             return minDepth(root.right)+1;10         return Math.min(minDepth(root.right),minDepth(root.left))+1;11     }

 

Balanced Binary Tree

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

新定義一個函數,表示樹的高度,如果是平衡樹的話。不是平衡樹則置高度為-1. 運用分治法遞迴,最後得到結果為-1則不是平衡的。基本情況,root==null則高度為0

 1     public boolean isBalanced(TreeNode root) { 2         if(height(root)==-1) 3             return false; 4         return true; 5     } 6     public int height(TreeNode root) 7     { 8         if(root==null) 9             return 0;10         int left = height(root.left);11         int right = height(root.right);12         if(left==-1 || right==-1)13             return -1;14         if(Math.abs(left-right)>1)15             return -1;16         return Math.max(left,right)+1;17     }

 

[Leetcode][JAVA] Minimum Depth of Binary Tree && Balanced Binary Tree

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.