110 Balanced Binary Tree 平衡二叉樹
阿新 • • 發佈:2018-04-05
treenode bool CP dep rip ems https node tco
給定一個二叉樹,確定它是高度平衡的。
對於這個問題,一棵高度平衡二叉樹的定義是:
一棵二叉樹中每個節點的兩個子樹的深度相差不會超過 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 。
詳見:https://leetcode.com/problems/balanced-binary-tree/description/
/** * 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 isBalance=true; bool isBalanced(TreeNode* root) { if(root==nullptr) { return true; } getDepth(root); return isBalance; } int getDepth(TreeNode* root) { if(root==nullptr) { return 0; } int left=getDepth(root->left); int right=getDepth(root->right); if(abs(left-right)>1) { return isBalance=false; } return max(left,right)+1; } };
110 Balanced Binary Tree 平衡二叉樹