zoukankan      html  css  js  c++  java
  • 110. 平衡二叉树

    自底向上递归的做法类似于后序遍历,对于当前遍历到的节点,先递归地判断其左右子树是否平衡,再判断以当前节点为根的子树是否平衡。

    如果一棵子树是平衡的,则返回其高度(高度一定是非负整数),否则返回 −1。如果存在一棵子树不平衡,则整个二叉树一定不平衡。

    /**
     * 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:
        bool isBalanced(TreeNode* root) {
            return dfs(root) >= 0;
        }
    
        int dfs(TreeNode* root) {
            if (!root) return 0;
            
            int leftDepth = dfs(root->left);
            if (leftDepth == -1) return -1;
            
            int rightDepth = dfs(root->right);
            if (rightDepth == -1) return -1;
            
            if (abs(leftDepth - rightDepth) > 1)
                return -1;
            
            return max(leftDepth, rightDepth) + 1;
        }
    };
    
  • 相关阅读:
    alpha冲刺9
    alpha冲刺8
    alpha冲刺7
    alpha冲刺6
    团队作业——随堂小测(同学录)
    alpha冲刺5
    【麻瓜制造者】团队项目测试报告与用户反馈
    Android基础学习
    学习博客之工具的学习、安装和使用
    学习博客之Java继承多态接口
  • 原文地址:https://www.cnblogs.com/fxh0707/p/15093522.html
Copyright © 2011-2022 走看看