LeetCode刷題Easy篇 Balanced Binary Tree
阿新 • • 發佈:2018-12-05
題目
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]
:
1
/ \
2 2
/ \
3 3
/ \
4 4
我的嘗試
用遞迴的思路,前面寫過一個就二叉樹最大深度的演算法,利用遞迴計算出左子樹和右子樹的最大深度,判斷abs絕對值是否小於等於1.程式碼如下:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public int maxDepth(TreeNode node){ if(node==null) return 0; return Math.max(maxDepth(node.left),maxDepth(node.right))+1; } public boolean isBalanced(TreeNode root) { if(root==null) return true; return Math.abs(maxDepth(root.left)-maxDepth(root.right))<=1; } }
但是有問題,我理解的情況有偏差,如果下面的情況不正確,因為節點2的左子樹是3,4但是右子樹為空。
我這個演算法,比較的是左側的最大深度和右側的最大深度差值,如果是左側的兩個深度比較呢?顯然沒有覆蓋這個情況。
下面進行修改:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public int maxDep(TreeNode node){ if(node==null) return 0; return 1+Math.max(maxDep(node.left),maxDep(node.right)); } public boolean isBalanced(TreeNode root) { if(root==null) return true; int diff=Math.abs(maxDep(root.left)-maxDep(root.right)); if(diff>1){ return false; } return isBalanced(root.left)&& isBalanced(root.right); } }