Leetcode 110. Balanced Binary Tree
2018-02-08 09:12
387 查看
原题:
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.
Example 1:
Given the following tree
/ \
9 20
/ \
15 7Return true.
Example 2:
Given the following tree
/ \
2 2
/ \
3 3
/ \
4 4
Return false.
解决方法:
依然可以用递归。
这里写了一个新函数,返回结果在函数函数参数里面返回,函数返回值返回数的深度。这样的写法在以后的解法中会多次用到。
代码:
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.
Example 1:
Given the following tree
[3,9,20,null,null,15,7]: 3
/ \
9 20
/ \
15 7Return true.
Example 2:
Given the following tree
[1,2,2,3,3,null,null,4,4]: 1
/ \
2 2
/ \
3 3
/ \
4 4
Return false.
解决方法:
依然可以用递归。
这里写了一个新函数,返回结果在函数函数参数里面返回,函数返回值返回数的深度。这样的写法在以后的解法中会多次用到。
代码:
int getDepth(TreeNode* root, bool& res){ if (!root){ res = true; return 0; } bool leftMatch = false, rightMatch = false; int left = getDepth(root->left, leftMatch), right = getDepth(root->right, rightMatch) ; res = leftMatch && rightMatch &&(abs(left - right) <= 1) ; return 1 + max(left, right); } bool isBalanced(TreeNode* root) { bool res = false; getDepth(root, res); return res; }
相关文章推荐
- 【leetcode】110. Balanced Binary Tree【java】
- [leetcode: Python] 110. Balanced Binary Tree
- leetCode 110. Balanced Binary Tree 平衡二叉树
- leetcode 110. Balanced Binary Tree
- leetcode-java-110. Balanced Binary Tree
- 110.[Leetcode]Balanced Binary Tree
- leetcode 110. Balanced Binary Tree-平衡二叉树|深度遍历
- leetcode -- 110. Balanced Binary Tree 【二叉树是否平衡】
- LeetCode 110. Balanced Binary Tree 递归求解
- 【LeetCode】 110. Balanced Binary Tree
- LeetCode解题报告 110. Balanced Binary Tree
- LeetCode 110. Balanced Binary Tree
- Leetcode#110. Balanced Binary Tree(判断是否是平衡二叉树)
- [LeetCode] 110. Balanced Binary Tree 解题思路
- 【leetcode】110.Balanced Binary Tree
- leetcode-110. Balanced Binary Tree
- LeetCode 110. Balanced Binary Tree
- leetcode 110. Balanced Binary Tree
- [Leetcode]110. Balanced Binary Tree
- [leetcode]110. Balanced Binary Tree