LeetCode日常刷題110
阿新 • • 發佈:2018-12-31
110. 平衡二叉樹
給定一個二叉樹,判斷它是否是高度平衡的二叉樹。
本題中,一棵高度平衡二叉樹定義為:
一個二叉樹每個節點 的左右兩個子樹的高度差的絕對值不超過1。
示例 1:
給定二叉樹 [3,9,20,null,null,15,7]
3 / \ 9 20 / \ 15 7
返回 true
。
示例 2:
給定二叉樹 [1,2,2,3,3,null,null,4,4]
1 / \ 2 2 / \ 3 3 / \ 4 4
返回 false
。
二叉平衡樹定義為:binary tree in which the depth of the two subtrees of every
即任意一個節點的兩個子樹深度差不超過1.
先寫一個函式遞迴得到任意一個節點的深度,
判斷是否為平衡樹的條件為:
1.根節點為空,是
2.根節點不為空,左右兩子樹的深度差1以上,不是
3.左右兩子樹的深度差1以內,如果兩個子樹都是平衡樹,則是,否則不是
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ static auto x = [](){ std::ios::sync_with_stdio(false); std::cin.tie(NULL); return 0; }(); class Solution { public: bool isBalanced(TreeNode* root) { if(root == NULL)return true; int h = 0; return helper(root, h); } private: bool helper(TreeNode* root, int& h){ int l = 0, r = 0; if(root->left) if(!helper(root->left, l))return false; if(root->right) if(!helper(root->right, r))return false; if(l - r > 1 || r - l > 1)return false; h = max(l, r) + 1; return true; } };
/** * 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 { private: int depth(TreeNode* root) { if (root == NULL) { return 0; } else { int left_depth = depth(root->left); int right_depth = depth(root->right); if (left_depth == -1 || right_depth == -1 || (left_depth - right_depth > 1) || (left_depth - right_depth < -1)) return -1; else if (left_depth - right_depth > 0) return left_depth + 1; else return right_depth + 1; } } public: bool isBalanced(TreeNode *root) { if (root == NULL) return true; else return (depth(root) !=-1); } };