Leetcode 平衡樹判別

判斷一顆二叉樹是否平衡。

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int heightOfTree(TreeNode root){
        if(root == null) return 0;
        return Math.max(heightOfTree(root.left), heightOfTree(root.right)) + 1;
    }

    public boolean isBalanced(TreeNode root) {
        if(root == null) return true;
        if((Math.abs(heightOfTree(root.left) - heightOfTree(root.right)) < 2) && isBalanced(root.left) && isBalanced(root.right)) return true;
        
        else return false;
    }
}


發佈了50 篇原創文章 · 獲贊 0 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章