標籤:
遞迴
- 左子樹是否為平衡二叉樹
- 右子樹是否為平衡二叉樹
- 左右子樹高度差是否大於1,大於1,返回false
- 否則判斷左右子樹
最簡單的理解方法就是如下的思路:
class Solution {public: bool isBalanced(TreeNode* root) { if(root==NULL){ return true; } int ldepth=depth(root->left); int rdepth=depth(root->right); if(abs(ldepth-rdepth)>1)return false; else{ return isBalanced(root->left)&&isBalanced(root->right); } } int depth(TreeNode *root){ if(root==NULL){ return 0; } int lleft=depth(root->left); int trigth=depth(root->right); return lleft>trigth ? lleft+1:trigth+1; }};
在上面的方法中,每一個節點都會計算節點左子樹和右子樹的高度,存在大量的重複計算
所以,採用自底向上的方式
class Solution2 {public: bool isBalanced(TreeNode* root) { if(root==NULL){ return true; } int height=getheight(root); if(height==-1){ return false; } return true; } int getheight(TreeNode *root){ if(root==NULL){ return 0; } int lleft=getheight(root->left); int trigth=getheight(root->right); if(lleft==-1||trigth==-1){ return -1; } if(abs(lleft-trigth)>1){ return -1; } return lleft>trigth? lleft+1:trigth+1; }};
Balanced Binary Tree --Leetcode C++