Leetcode:110. 平衡二叉樹html
點連接就能看到原題啦~node
關於AVL的判斷函數寫法,請跳轉:平衡二叉樹的判斷函數
廢話不說直接上代碼吧~主要的解析的都在上面的連接裏了code
/** * 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 getHeight(TreeNode* root){ if(root==NULL) return 0; return max(getHeight(root->right),getHeight(root->left))+1; } bool isBalanced(TreeNode* root) { if(root==NULL) return true; if(isBalanced(root->left)&&isBalanced(root->right)) if(abs(getHeight(root->left)-getHeight(root->right))<2) return true; return false; } };
/** * 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 isBalancedHelper(TreeNode* root,int& height){ if(root==NULL){ height=0; return true; } int left,right; if(isBalancedHelper(root->right,right)&&isBalancedHelper(root->left,left)&&abs(left-right)<2){ height=max(left,right)+1; return true; } return false; } bool isBalanced(TreeNode* root) { int height=0; return isBalancedHelper(root,height); } };