[Leetcode] [JAVA] Minimum Depth of binary tree && Balanced binary tree

Source: Internet
Author: 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 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.