【LeetCode】110. Balanced Binary Tree(Easy)解题报告
2018-03-17 20:07
489 查看
【LeetCode】110. Balanced Binary Tree(Easy)解题报告
题目地址:https://leetcode.com/problems/balanced-binary-tree/description/
题目描述:
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.
Solution:
Date:2018年3月17日
题目地址:https://leetcode.com/problems/balanced-binary-tree/description/
题目描述:
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 7 Return 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.
Solution:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } 判断是不是高度平衡,左右子树高度差值是否大于一 后序遍历判断左右子树高度 time : O(n) space : O(n) */ class Solution { public boolean isBalanced(TreeNode root) { if(root == null) return true; return helper(root)!=-1; } public int helper(TreeNode root){ if(root == null) return 0; int l = helper(root.left); int r = helper(root.right); if(l == -1 || r == -1 || Math.abs(l-r)>1){ return -1; } return Math.max(l,r)+1; } }
Date:2018年3月17日
相关文章推荐
- LeetCode解题报告 110. Balanced Binary Tree [easy]
- Leetcode 110. Balanced Binary Tree 平衡二叉树 解题报告
- [leetcode]110. Balanced Binary Tree@Java解题报告
- [Leetcode] 110. Balanced Binary Tree 解题报告
- [leetcode] 110. Balanced Binary Tree 解题报告
- LeetCode解题报告 110. Balanced Binary Tree
- 【LeetCode】637.Average of Levels in Binary Tree(Easy)解题报告
- Leetcode 110. Balanced Binary Tree (Easy) (cpp)
- 【LeetCode】Balanced Binary Tree 解题报告
- LeetCode解题报告 104. Maximum Depth of Binary Tree [easy]
- leetCode 110.Balanced Binary Tree (平衡二叉树) 解题思路和方法
- 【LeetCode】Balanced Binary Tree 解题报告
- 【LeetCode】235.Lowest Common Ancestor of a Binary Search Tree(Easy)解题报告
- LeetCode解题报告 111. Minimum Depth of Binary Tree [easy]
- LeetCode(110) Balanced Binary Tree解题报告
- 【LeetCode】270.Closest Binary Search Tree Value(Easy)解题报告
- 【LeetCode】111.Minimum Depth of Binary Tree(Easy)解题报告
- 【LeetCode】226.Invert Binary Tree(Easy)解题报告
- 【LeetCode】108.Convert Sorted Array to Binary Search Tree(Easy)解题报告
- LeetCode: Balanced Binary Tree 解题报告