youngyangyang04 / leetcode-master-comment

用来做评论区
0 stars 0 forks source link

[Vssue]0110.平衡二叉树.md #72

Open youngyangyang04 opened 3 months ago

youngyangyang04 commented 3 months ago

https://www.programmercarl.com/0110.%E5%B9%B3%E8%A1%A1%E4%BA%8C%E5%8F%89%E6%A0%91.html

Du1in9 commented 2 months ago
class Solution {
    private int getHeight(TreeNode node){
        if(node == null) return 0;
        int h1 = getHeight(node.left);  // 左子树高度
        if(h1 == -1) return -1;
        int h2 = getHeight(node.right); // 右子树高度
        if(h2 == -1) return -1;
        if(Math.abs(h1 - h2) > 1) return -1;
        return 1 + Math.max(h1, h2);    // 此节点高度
    }
    public boolean isBalanced(TreeNode root) {
        return getHeight(root) == -1 ? false : true;
    }
}
imGallon commented 1 month ago

不是很理解迭代法getDepth如果是用求最大深度的方法求高度的话为什么说不能用层序遍历来求?我以下getDepth代码用的是层序遍历也能通过呀 int getDepth(TreeNode root) { std::queue<TreeNode> que; int dep = 0; if (root != nullptr) que.push(root); while (!que.empty()) { dep++; int size = que.size(); for (int i = 0; i < size; i++) { TreeNode* node = que.front(); que.pop(); if (node->left) que.push(node->left); if (node->right) que.push(node->right); } } return dep; }