LeetCode 110. Balanced Binary Tree (平衡二叉树)
2017-07-04 00:36
483 查看
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.
题目标签:Tree
这道题目给了我们一个 二叉树, 让我们来判断一下它是否是一个 height-balanced 二叉树。 先来看一下什么是 height-balanced 二叉树, 对于每一个点,它的左边子树的depth 和右边子树的 depth 不能相差多余1。这道题目可以利用getDepth 来帮助我们判断。getDepth function 是通过递归,利用postOrder来从树的最低端走起,当点是null时候,就返回depth 0, 每次返回depth + 1, 那么我们可以多加一个if statement 在 一个parent 点拿到左边的depth 和右边的depth 之后, 如果左边和右边的相差值,大于1,那么 把我们预先设的 boolean is_balanced 改为false。
Java Solution:
Runtime beats 25.84%
完成日期:07/03/2017
关键词:Tree
关键点:利用 getDepth function
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { boolean is_balanced = true; public boolean isBalanced(TreeNode root) { getDepth(root); return is_balanced; } public int getDepth(TreeNode node) { if(node == null) return 0; int left_depth = getDepth(node.left); int right_depth = getDepth(node.right); if(Math.abs(left_depth - right_depth) > 1) is_balanced = false; return Math.max(left_depth, right_depth) + 1; } }
参考资料:N/A
LeetCode 算法题目列表 - LeetCode Algorithms Questions List
相关文章推荐
- leetcode 110. Balanced Binary Tree(平衡二叉树的判断) DFS深度优先遍历
- leetcode 110. Balanced Binary Tree 判断是否是一颗平衡二叉树
- 剑指offer 面试题39:判断平衡二叉树(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 | Balanced Binary Tree(平衡二叉树)
- 【leetcode】110. Balanced Binary Tree
- 二叉树递归问题 leetcode 572. Subtree of Another Tree & leetcode 110. Balanced Binary Tree
- leetcode Balanced Binary Tree 平衡二叉树判定
- LeetCode *** 110. Balanced Binary Tree