[Leedcode 110] Balanced Binary Tree

Source: Internet
Author: User

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.

/*** Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode rig Ht * TreeNode (int x) {val = x;} }*/ Public classSolution { Public Booleanisbalanced (TreeNode root) {//you need to construct a function to calculate the height of a node, and then each layer of the isbalanced function starts to verify that the left and right sub-trees meet the requirements, and this idea is very intuitive.//This method is not efficient, because when each node is satisfied, it needs to be highly re-verified, then the next layer, the intermediate calculation has a repeating calculation//Another optimization algorithm, when the height of the information can be returned directly, the default direct return 1, do not need to compare        if(root==NULL)return true; intleft=getdepth (Root.left); intright=getdepth (root.right); if(left>right+1| | RIGHT>LEFT+1)return false; Else{            returnisbalanced (Root.left) &&isbalanced (root.right); }    }    intgetdepth (TreeNode root) {if(root==NULL)return0; returnMath.max (Getdepth (Root.left), getdepth (root.right)) +1; }        /*Public Boolean isbalanced (TreeNode root) {int temp=getdepth (root);    Return temp>-1;        } public int getdepth (TreeNode root) {if (root==null) return 0;        int left=getdepth (root.left);        int right=getdepth (root.right);        int Temp=math.abs (left-right); if (left==-1| | right==-1| |               temp>1) return-1;    Return left>right?left+1:right+1; }*/}

[Leedcode] 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.