題意:
給定一個二叉樹,判斷它是否是高度平衡的二叉樹。
本題中,一棵高度平衡二叉樹定義為:
一個二叉樹每個節點 的左右兩個子樹的高度差的絕對值不超過1。
示例 1:
給定二叉樹 [3,9,20,null,null,15,7]
3 / \ 9 20 / \ 15 7
返回 true
。
示例 2:
給定二叉樹 [1,2,2,3,3,null,null,4,4]
1 / \ 2 2 / \ 3 3 / \ 4 4
返回 false
。
思路:
什么是平衡二叉平衡樹?
左右子樹的深度差的絕對值不大於1
左子樹和右子樹也都是平衡二叉樹
所以我們只需要在求一棵樹的深度的代碼中加上高度差判斷就可以
代碼:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int judge(TreeNode* root,bool &ans) { if(root) { int ans1 = judge(root->left,ans); int ans2 = judge(root->right,ans); if(abs(ans1-ans2)>1) ans=false; return max(ans1,ans2)+1; } else return 0; } bool isBalanced(TreeNode* root) { bool ans = true; judge(root,ans); return ans; } };