zoukankan      html  css  js  c++  java
  • java 递归实现平衡二叉树

    public class 平衡二叉树
    {
        public class TreeNode
        {
            TreeNode left;
            TreeNode right;
            int val;

            TreeNode(int x)
            {
                this.val = x;
            }
        }

        // 获取深度
        private int getDepth(TreeNode tree, int currentDepth)
        {
            if (tree == null)
            {
                return currentDepth;
            }
            return Math.max(getDepth(tree.left, currentDepth + 1),
                    getDepth(tree.right, currentDepth + 1));

        }

        // 采用递归解决
        public boolean isBalanced(TreeNode root)
        {
            if (root == null)
            {
                return true;
            }
            int depthOfLeft = getDepth(root.left, 1);
            int depthOfRight = getDepth(root.right, 1);
            if (Math.abs(depthOfLeft - depthOfRight) > 1)
            {
                return false;
            }
            else
            {
                return isBalanced(root.left) && isBalanced(root.right);
            }
        }
    }

  • 相关阅读:
    CMake学习笔记
    右键添加"在此处打开命令窗口"菜单
    设置默认python模块源
    添加到附加组
    Unity宏处理
    挂载windows共享文件夹
    MacOS长按无效问题
    中文Locale
    笔记本用作无线路由器
    C# Winfrom iTextSharp 导出pdf 带二维码 表格嵌套 简单Dome
  • 原文地址:https://www.cnblogs.com/qingtianBKY/p/6915417.html
Copyright © 2011-2022 走看看