Leetcode 110 平衡二叉樹
阿新 • • 發佈:2020-12-01
Leetcode 110 平衡二叉樹
資料結構定義:
給定一個二叉樹,判斷它是否是高度平衡的二叉樹。
本題中,一棵高度平衡二叉樹定義為:
一個二叉樹每個節點 的左右兩個子樹的高度差的絕對值不超過 1 。
示例 1:
輸入:root = [3,9,20,null,null,15,7]
輸出:true
輸入:root = [1,2,2,3,3,null,null,4,4]
輸出:false
輸入:root = []
輸出:true
自底向上寫法:
class Solution { public boolean isBalanced(TreeNode root) { if(root == null){ return true; } return dfs(root) != -1; } private int dfs(TreeNode root){ if(root == null){ return 0; } int left = dfs(root.left); int right = dfs(root.right); if(left == -1 || right == -1 || Math.abs(left - right) > 1){ return -1; } return Math.max(left,right) + 1; } }
自頂向下:
class Solution { public boolean isBalanced(TreeNode root) { if (root == null) { return true; }else { return Math.abs(height(root.left) - height(root.right)) <= 1 && isBalanced(root.left) && isBalanced(root.right); } } private int height(TreeNode root) { if (root == null) { return 0; } return Math.max(height(root.left), height(root.right)) + 1; } }