版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
重复遍历多次的解法 简单
上题求二叉树的深度,想到一种思路:遍历树的每个节点的时候,调用函数TreeDepth得到他的左右子树深度,,如果每个节点左右子树深度相差都不超过1,那么就是平衡二叉树。
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(root==null)
return true;
int left=TreeDepth(root.left);
int right=TreeDepth(root.right);
int diff=left-right;
if(diff>1||diff<-1)
return false;
return IsBalanced_Solution(root.left)&&IsBalanced_Solution(root.right);
}
public int TreeDepth(TreeNode root){
if(root==null)
return 0;
int left=TreeDepth(root.left);
int right=TreeDepth(root.right);
return 1+Math.max(left,right);
}
}
效率不高,如判断2节点时会判断4、5、7,接下来判断2节点是还要判断4、5、7,重复了
每个节点只遍历一次的方法 后序遍历 面试官喜欢
**后续遍历方式,遍历到一个节点之前我们就已经便利了他的左右子树,**只要在遍历每个节点的时候记录它的深度,就可以一边遍历一边判断是不是平衡的。
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
return getDepth(root)!=-1;
}
public int getDepth(TreeNode root){
if(root==null)
return 0;
int left=getDepth(root.left);
int right=getDepth(root.right);
if( left==-1 || right==-1|| Math.abs(left-right)>1)
return -1;
return 1 + Math.max(left,right);
}
}