LeetCode-Balanced Binary Tree
生活随笔
收集整理的這篇文章主要介紹了
LeetCode-Balanced Binary Tree
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
平衡二叉樹的判斷,DFS,
一直沒想到怎么同時返回結點的長度和狀態,把高度放到參數里面比較簡便!
1 class Solution { 2 public: 3 bool isBalanced(TreeNode *root) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 int height = 0; 7 return getHeight(root, height); 8 9 } 10 bool getHeight(TreeNode *root, int &height) { 11 if (!root) { 12 return true; 13 } 14 int leftheight = 0; 15 int rightheight = 0; 16 if (getHeight(root->left, leftheight) && getHeight(root->right, rightheight)) { 17 height = max(leftheight, rightheight) + 1; 18 if (abs(leftheight - rightheight) <= 1) { 19 return true; 20 } 21 } 22 return false; 23 } 24 };?不過其實不需要用兩個變量來表示狀態,可以直接用一個int返回值來表示,
?如果是false的則直接返回-1,否則返回高度:
1 class Solution { 2 public: 3 bool isBalanced(TreeNode *root) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 int ret = getHeight(root); 7 if (ret == -1) { 8 return false; 9 } 10 return true; 11 } 12 int getHeight(TreeNode *root) { 13 if (root == NULL) { 14 return 0; 15 } 16 int left = getHeight(root->left); 17 int right = getHeight(root->right); 18 if (left == -1 || right == - 1) { 19 return -1; 20 } 21 if (abs(left - right) > 1) { 22 return -1; 23 } 24 return (max(left, right) + 1); 25 } 26 };?
轉載于:https://www.cnblogs.com/chasuner/p/balanced.html
總結
以上是生活随笔為你收集整理的LeetCode-Balanced Binary Tree的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [Boost基础]并发编程——asio网
- 下一篇: 两种比较不错的密码修改方案