Leetcode: Balanced Binary Tree
生活随笔
收集整理的這篇文章主要介紹了
Leetcode: Balanced Binary Tree
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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.
很鍛煉DP/recursive思路的一道題,個人感覺DP/recursive算是比較難寫的題目了。這道題解法的巧妙之處在于巧用-1,并且使用臨時存儲,節省了很多開支。這道題同時也在Career Cup上面出現過
這道題我兩次調試通過,第一次錯是因為input{}, output false, expected true
我的算法只有一層遞歸(因為巧用-1的原因),runs in O(N) time, andO(H) space
1 public class Solution { 2 public boolean isBalanced(TreeNode root) { 3 if (root == null) return true; 4 if (checkBalance(root) != -1) return true; 5 else return false; 6 } 7 8 public int checkBalance(TreeNode root) { 9 if (root == null) return 0; 10 int leftHeight = checkBalance(root.left); 11 int rightHeight = checkBalance(root.right); 12 if (leftHeight == -1 || rightHeight == -1) return -1; 13 else if (Math.abs(leftHeight - rightHeight) > 1) return -1; 14 return Math.max(leftHeight, rightHeight) + 1; 15 } 16 }?
?
總結
以上是生活随笔為你收集整理的Leetcode: Balanced Binary Tree的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CentOS通过DNSpod实现动态域名
- 下一篇: 数据库如何闪回到某个时间点?