zoukankan      html  css  js  c++  java
  • #树#判断平衡二叉树

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public boolean isBalanced(TreeNode root) {
            if(root == null) return true;
            height(root);
            return this.flag;
    
        }
        private boolean flag = true;
        // public int height(TreeNode h) {
        //     if(h==null) return 0;
        //     return 1+ Math.max(height(h.left), height(h.right));
        // }
        // public void dfs(TreeNode h) {
        //     if(h==null) return;
        //     if(flag==false) return;
        //     int left = height(h.left);
        //     int right = height(h.right);
            
        //     if(Math.abs(left-right)>1) {
        //         flag = false;
        //         return;
        //     }
        //     dfs(h.left);
        //     dfs(h.right);
        // }
    
        public int height(TreeNode h) {
            if(h == null || flag == false) return 0;
            int l = height(h.left)+1;
            int r = height(h.right)+1;
            if(Math.abs(l-r)>1) {
                flag = false;
            }
            return Math.max(l,r);
        }
    
    
    
    
    
    
    
    
    
    
    
    }
  • 相关阅读:
    第十二周作业
    第十一周作业
    第十周作业
    第九周作业*
    #**第八周作业+预习作业**
    第七周作业
    Linux 日志查看常用命令
    Linux tar命令
    Java 数组
    设计模式 观察者模式(Observer)
  • 原文地址:https://www.cnblogs.com/lyr-2000/p/13301697.html
Copyright © 2011-2022 走看看