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 to the nearest leaf node.
Compare the depth of the Saozi right subtree, take the small one back up, and +1.
It is important to note that if there is no left sub-tree or right subtree. So unconditionally take the side subtree depth, and +1.
If Saozi right subtree is not, then the leaf node, return depth 1.
If root itself is NULL, returns 0
1 Public intmindepth (TreeNode root) {2 if(root==NULL)3 return0;4 if(root.left==NULL&& root.right==NULL)5 return1;6 if(root.right==NULL)7 returnMindepth (Root.left) +1;8 if(root.left==NULL)9 returnMindepth (root.right) +1;Ten returnMath.min (Mindepth (root.right), mindepth (root.left)) +1; One}
Balanced Binary Tree
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree was defined as a binary tree in which the depth of the Every node never differ by more than 1.
Define a new function that represents the height of the tree, if it is a balanced tree. Not the balance tree the set height is-1. By using the method of division and recursion, the result of which is 1 is not balanced. Basic situation, Root==null height is 0
1 Public Booleanisbalanced (TreeNode root) {2 if(Height (root) ==-1)3 return false;4 return true;5 }6 Public intheight (TreeNode root)7 {8 if(root==NULL)9 return0;Ten intleft =height (root.left); One intright =height (root.right); A if(Left==-1 | | right==-1) - return-1; - if(Math.Abs (left-right) >1) the return-1; - returnMath.max (left,right) +1; -}
[Leetcode] [JAVA] Minimum Depth of binary tree && Balanced binary tree