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.
就是去查看一棵树是不是平衡的,一开始对平衡二叉树的理解有错误,所以写错了 ,看了别人的解答之后更正过来了:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 bool isBalanced(TreeNode* root) { 13 int dep; 14 checkBalance(root, dep); 15 } 16 bool checkBalance(TreeNode * root, int &dep) 17 { 18 if(root == NULL){ 19 dep = 0; 20 return true; 21 } 22 int leftDep, rightDep; 23 bool isLeftBal = checkBalance(root->left, leftDep); 24 bool isRightBal = checkBalance(root->right, rightDep); 25 26 dep = max(leftDep, rightDep) + 1; 27 return isLeftBal && isRightBal && (abs(leftDep - rightDep) <= 1); 28 } 29 };
pS:感觉这个不应该easy的题目啊 想的时候头还挺疼的。。
LeetCode OJ:Balanced Binary Tree(平衡二叉树)
原文:http://www.cnblogs.com/-wang-cheng/p/4891070.html