Leetcode 110. Balanced Binary Tree
2017-02-03 14:00
399 查看
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.
s思路:
1. 判断是否balance,即:每个根节点的左子树和右子树的高度相差最多为1。考虑每个节点,可以用recursive来做。
2. 既然计算高度,那么用一个高度参数。
3. 稍微总结一下:在recursive的过程中,什么时候用reference?什么时候不用?比如这个题,就非用不可,因为统计高度,需要先recursive到底,然后把高度从底层传递到上层。我们知道,用reference是我们想把参数信息从底层往上层传递。而不需要用refenece的时候,就是我们不希望用底层的数据,上层不希望底层的参数干扰上层。这里唠叨这么多,其实就想加深印象:reference是把底层参数往上层传递的一个方法!
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.
s思路:
1. 判断是否balance,即:每个根节点的左子树和右子树的高度相差最多为1。考虑每个节点,可以用recursive来做。
2. 既然计算高度,那么用一个高度参数。
3. 稍微总结一下:在recursive的过程中,什么时候用reference?什么时候不用?比如这个题,就非用不可,因为统计高度,需要先recursive到底,然后把高度从底层传递到上层。我们知道,用reference是我们想把参数信息从底层往上层传递。而不需要用refenece的时候,就是我们不希望用底层的数据,上层不希望底层的参数干扰上层。这里唠叨这么多,其实就想加深印象:reference是把底层参数往上层传递的一个方法!
//方法1:recursive class Solution { public: bool helper(TreeNode* root,int&height){ // if(!root){height=0;return true;} int h1,h2; if(helper(root->left,h1)&&helper(root->right,h2)&&abs(h1-h2)<=1){ height=max(h1,h2)+1; return true; } return false; } bool isBalanced(TreeNode* root) { // int height=0; return helper(root,height); } };
相关文章推荐
- [Leetcode] 110. Balanced Binary Tree 解题报告
- [LeetCode] 110. Balanced Binary Tree 平衡二叉树
- leetcode 110. Balanced Binary Tree(平衡二叉树的判断) DFS深度优先遍历
- 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 572. Subtree of Another Tree & leetcode 110. Balanced Binary Tree
- LeetCode 110. Balanced Binary Tree
- Leetcode 110. Balanced Binary Tree
- [leetcode: Python] 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