标签:
Balanced Binary Tree
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.
树的深度是从根节点开始(其深度为1)自顶向下逐层累加的,而高度是从叶节点开始(其高度为1)自底向上逐层累加的。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { private: bool balance = true; int height(TreeNode *root) { if(!balance) return -1; if(root==NULL) return 0; else { int left_height = height(root->left)+1; int right_height = height(root->right)+1; if( abs(left_height-right_height) > 1) balance = false; else return left_height>right_height ? left_height : right_height; } } public: bool isBalanced(TreeNode *root) { height(root); return balance; } };
leetcode_110_ Balanced Binary Tree
标签:
原文地址:http://blog.csdn.net/keyyuanxin/article/details/43865245