標籤:
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