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 binary tree 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 key; 13 bool isBalanced(TreeNode *root) { 14 // Start typing your C/C++ solution below 15 // DO NOT write int main() function 16 key = true; 17 DepthFirst(root); 18 return key; 19 } 20 int DepthFirst(TreeNode *root) 21 { 22 if(root == NULL) 23 return 0; 24 int lDepth = DepthFirst(root->left); 25 if(key == false) 26 return -1; 27 int rDepth = DepthFirst(root->right); 28 if(key == false) 29 return -1; 30 if(lDepth > rDepth + 1 ||rDepth > lDepth + 1) 31 { 32 key = false; 33 return -1; 34 } 35 int max = (lDepth >= rDepth)?lDepth:rDepth; 36 return 1 + max; 37 } 38 };

浙公网安备 33010602011771号