LeetCode, leetcodeoj

Source: Internet
Author: User

LeetCode, leetcodeoj
Description:


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.


Is to judge whether a tree is a Balance Tree.


The height difference between left and right decision trees cannot exceed 1.


Ideas:


Determine whether each node is balanced
For any node, determine whether the left and right sides are balanced. The current tree is balanced only when both left and right trees are balanced.
Calculate the height of left and right subtree respectively, and return Math. Max (height of left subtree, height of right subtree) + 1




Implementation Code:




/** * Definition for a binary tree node. * public class TreeNode { *     public int val; *     public TreeNode left; *     public TreeNode right; *     public TreeNode(int x) { val = x; } * } */public class Solution {    public bool IsBalanced(TreeNode root)     {        if(root == null || root.left == null && root.right == null){    return true;    }        var l = Depth(root.left);    var r = Depth(root.right);    if(Math.Abs(l-r) > 1){    return false;    }        var bLeft = IsBalanced(root.left);    var bRight = IsBalanced(root.right);    return bLeft && bRight;    }    public int Depth(TreeNode node)    {        if(node == null){        return 0;        }                var l = Depth(node.left);        var r = Depth(node.right);        var len = Math.Max(l,r);    return len + 1;    }}


Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.