LeetCode[110]平衡二叉树

思路:

本题解法依旧是后序遍历,采用左右根来解决,如果你要采用前序遍历什么的,你需要先计算根节点,那根节点的计算又要计算子节点,然后再递归左右,这样子节点就会被重复计算,对时间复杂度来说不太友好,属于O(nlog(n))时间复杂度。

但采用后序遍历就不一样了,只需要把每个节点都遍历一下就能得出答案,所以时间复杂度为O(n), 高下立判

代码:

java 复制代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean isBalanced(TreeNode root) {
        return getHeight(root) != -1;
    }

    public int getHeight(TreeNode root) {
        if (root == null)
            return 0;
        int leftHeight = getHeight(root.left);
        if (leftHeight == -1)
            return -1;
        int rightHeight = getHeight(root.right);
        if (rightHeight == -1)
            return -1;

        if (Math.abs(leftHeight - rightHeight) > 1) {
            return -1;
        }

        return Math.max(leftHeight, rightHeight) + 1;
    }
}
相关推荐
民乐团扒谱机16 小时前
【超详细】基频音高提取算法之SWIPE 算法深度解析:频谱匹配的精度极限与工程边界
人工智能·算法
饮水桶_T16 小时前
C++ stack & queue复习笔记
开发语言·笔记·算法
wy_hhxx17 小时前
[Leetcode] 滑动窗口
算法·leetcode·滑动窗口
码途行者17 小时前
每天10分钟学Go:第20课 泛型
c++·算法·golang
AIgorithmGEEK19 小时前
算法·哈希表|从“逐个比”到“按 key 算位置”
数据结构·c++·算法·leetcode·hash
风落青芜21 小时前
排序算法(二):选择排序、堆排序与冒泡排序
c语言·开发语言·数据结构·算法·排序算法
Navigator_Z1 天前
LeetCode //C - 1319. Number of Operations to Make Network Connected
c语言·算法·leetcode
h_a_o777oah1 天前
【数据结构】FHQ Treap:无旋转的平衡 BST
数据结构·c++·算法·acm·平衡树·treap·fhq treap
草履虫AI课1 天前
强化学习从零到一 07|重要性采样:借别人的数据,算自己的期望
算法·强化学习