目录
一:题目:
给定一个二叉树,判断它是否是
平衡二叉树
二:代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int account(TreeNode* node){
if(!node) return 0;
stack<TreeNode*> st;
int depth=0;
int result=0;
st.push(node);
while(!st.empty()){
TreeNode* p=st.top();
if(p!=nullptr){
st.pop();
st.push(p);
st.push(nullptr);
depth++;
if(p->right) st.push(p->right);
if(p->left) st.push(p->left);
}else{
st.pop();
p=st.top();
st.pop();
depth--;
}
result=result>depth?result:depth;
}
return result;
}
bool isBalanced(TreeNode* root) {
stack<TreeNode*> st;
if(!root) return true;
st.push(root);
while(!st.empty()){
TreeNode* p=st.top();
st.pop();
if(abs(account(p->left)-account(p->right))>1){
return false;
}
if(p->left) st.push(p->left);
if(p->right) st.push(p->right);
}
return true;
}
};