LeetCode 110. Balanced Binary Tree
本来只是简单地比较两棵子树的高度,但是看到题目中的every node就想偏了。
实际上就是计算左右子树的高度差是否大于1.
思路:求树的height,某个节点的height = max(左子树height,右子树height) + 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 getHeight(TreeNode* root, int &height){ 13 if(root == NULL){ 14 height = 0; 15 return true; 16 } 17 // cout<<height<<endl; 18 int leftH = 0, rightH = 0; 19 if(!getHeight(root->left, leftH)) return false; 20 if(!getHeight(root->right, rightH)) return false; 21 if(abs(leftH - rightH) > 1) return false; 22 height = max(leftH, rightH) + 1; 23 return true; 24 } 25 bool isBalanced(TreeNode* root) { 26 if(root == NULL) return true; 27 int height = 0; 28 return getHeight(root, height); 29 } 30 31 32 };
还有其他算法,留坑。