LeetCode|Balanced Binary Tree-java
2015-09-26 16:27
561 查看
题目:
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.
思路:
判断一个二叉树是不是平衡二叉树(如果树所有节点的左子树和右子树的高度差不超过1就是平衡二叉树),这也是典型的递归算法题。对左右子树的高度作比较,然后递归分别对左右子树的孩子的高度继续做比较。
如果我们用后序遍历的方式遍历一遍二叉树的每一个节点,在遍历到一个节点之前我们就已经遍历了它的左右子树。只要在遍历每个节点的时候记录它的深度(某一节点的深度等于它到节点的路径的长度),我们一遍遍历一遍判断每个节点是不是平衡的。
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.
思路:
判断一个二叉树是不是平衡二叉树(如果树所有节点的左子树和右子树的高度差不超过1就是平衡二叉树),这也是典型的递归算法题。对左右子树的高度作比较,然后递归分别对左右子树的孩子的高度继续做比较。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public static int maxDepth(TreeNode root) { if (root == null) { return 0; } int leftDepth = maxDepth(root.left); int rightDepth = maxDepth(root.right); return leftDepth > rightDepth ? (leftDepth + 1) : (rightDepth + 1); } public static boolean isBalanced(TreeNode root) { if (root == null) { return true; } int diff = Math.abs(maxDepth(root.left) - maxDepth(root.right)); return diff <= 1 && isBalanced(root.left) && isBalanced(root.right); } }
如果我们用后序遍历的方式遍历一遍二叉树的每一个节点,在遍历到一个节点之前我们就已经遍历了它的左右子树。只要在遍历每个节点的时候记录它的深度(某一节点的深度等于它到节点的路径的长度),我们一遍遍历一遍判断每个节点是不是平衡的。
相关文章推荐
- LeetCode|Path Sum-java
- java中static关键字的理解
- LeetCode|Pascal's Triangle-java
- struts1工作原理
- Java中finalize()用法
- java数组和向量
- Java之内存分析和String对象
- java中代理模式以及new和newInatance()的区别
- dos写helloworld程序总结 java 和 javac的使用
- JAVA 的普通加法运算
- Java Socket编程----通信是这样炼成的
- Java:instanceof用法
- java基础的一些概念.够自己有时间查看
- Java用ZIP进行多文件压缩保存
- Java的this关键字的使用与方法的重载相关知识
- Java用GZIP进行简单压缩
- test8.2
- 【Java基础第三弹】List集合的复制
- JAVA--读取csv文件并导数
- Java的访问修饰符与变量的作用域讲解