110. 平衡二叉樹 - 8月17日
阿新 • • 發佈:2020-08-17
題目
110. 平衡二叉樹
我的思路
遞迴解決: 後續遍歷,先得到當前節點兩棵子樹的高度,比較是否滿足條件;返回較大值作為當前節點的高度。每個節點作為根的高度之差我的實現
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution {public: bool result; int postSearch(TreeNode *root){ if(root==NULL)return 0; else{ int h1 = postSearch(root->left); int h2 = postSearch(root->right); if(h1-h2>1||h2-h1>1){ result = false; }return max(h1,h2)+1; } } bool isBalanced(TreeNode* root) { result = true; postSearch(root); return result; } }; /* 求節點高度, 球節點層次, 遞迴完成: 後續遍歷,先得到當前節點兩棵子樹的高度,比較是否滿足條件;返回較大值作為當前節點的高度。每個節點作為根的高度之差 */