zoukankan      html  css  js  c++  java
  • 剑指 Offer 55

    在这里插入图片描述

    后续遍历

     第一种解法是通过递归计算每个节点左右子树的深度,如果左右子树深度差都不超过1那么这棵树为平衡二叉树。
     上面的解法或重复遍历节点。为了解决这个问题可以使用后续遍历:遍历每个节点,在遍历一个节点是已经遍历了它的左子树和右子树。这样只需在遍历每个节点时记录它的深度值,就能一边遍历一边判断每个节点是不是平衡的,代码如下:

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        // 自定义引用类型,用于记录当前节点的深度值
        class Depth {
            int cur = 0;
        }
    
        public boolean isBalanced(TreeNode root) {
            return isBalancedCore(root, new Depth());
        }
    
        private boolean isBalancedCore(TreeNode root, Depth depth) {
            if (root == null) {
                depth.cur = 0;
                return true;
            }
            Depth left = new Depth();
            Depth right = new Depth();
            if (isBalancedCore(root.left, left) && isBalancedCore(root.right, right)) {
                int diff = left.cur - right.cur;
                if (diff <=1 && diff >= -1) {
                    depth.cur = Math.max(left.cur, right.cur) + 1;
                    return true;
                }
            }
            return false;
        }
    }
    
  • 相关阅读:
    ASP.NET获取客户端IP地址Marc地址
    WPF(MultiBinding 数据对比验证,启用提交)
    WPF(Binding of ObjectDataProvider)
    WPF(附加属性 Slider)
    WPF(Binding of ItemsControl)
    WPF( 数据验证)
    WPF(依赖属性)
    WPF(附加属性)
    WPF(Binding of RelativeSource)
    WPF(Binding of LinQ)
  • 原文地址:https://www.cnblogs.com/PythonFCG/p/13859933.html
Copyright © 2011-2022 走看看