日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Leetcode: Balanced Binary Tree

發布時間:2025/4/5 编程问答 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。