1. 程式人生 > 實用技巧 >#樹#判斷平衡二叉樹

#樹#判斷平衡二叉樹

/**
 * 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); } }