用后序遍历的方法做,可以避免重复遍历节点。在遍历到一个节点之前就已经遍历了它的左右子树

代码如下:

class Solution {
public:
    bool IsBalanced_Solution(TreeNode* pRoot) {
        bool flag=true;
        int tmp=getDepth(pRoot,flag);
        return flag;
    }
    
    int getDepth(TreeNode* root,bool &flag){
        if(!root)return 0;
        int left=getDepth(root->left,flag);
        int right=getDepth(root->right,flag);
        if(abs(left-right)>1)flag=false;
        
        return left>right?left+1:right+1;
    }
};

 

相关文章:

  • 2021-10-13
  • 2022-12-23
  • 2021-11-08
  • 2022-12-23
  • 2022-12-23
  • 2021-04-20
  • 2021-06-01
  • 2021-11-18
猜你喜欢
  • 2021-10-12
  • 2021-09-26
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案