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.