剑指offer算法题
树
题目描述
输入一棵二叉树,判断该二叉树是否是平衡二叉树。
在这里,我们只需要考虑其平衡性,不需要考虑其是不是排序二叉树。
题目分析
利用深度优先算法进行遍历,同时计算每个节点的左右子树最大深度。
方法一 非递归
下面是Java代码实现
import java.util.Stack;
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(root == null){
return true;
}
Stack<TreeNode> s = new Stack<>();
s.add(root);
int left = 0;
int right = 0;
while(!s.isEmpty()){
TreeNode tmp = s.pop();
left = TreeDepth(tmp.left);
right = TreeDepth(tmp.right);
if(Math.abs(right - left) > 1){
return false;
}
if(tmp.right != null){
s.add(tmp.right);
}
if(tmp.left !=null){
s.add(tmp.left);
}
}
return true;
}
//计算节点的最长路径为深度。
public int TreeDepth(TreeNode root) {
if(root == null){
return 0;
}
int left = TreeDepth(root.left);
int right = TreeDepth(root.right);
return Math.max(left , right) +1 ;
}
}
方法二 递归
下面是Java代码实现
public class Solution {
public boolean IsBalanced_Solution(TreeNode root) {
if(root == null){
return true;
}
int left = TreeDepth(root.left);
int right = TreeDepth(root.right);
if(Math.abs(left - right) >1){
return false;
}
IsBalanced_Solution(root.left);
IsBalanced_Solution(root.right);
return true;
}
public int TreeDepth(TreeNode root) {
if(root == null){
return 0;
}
int left = TreeDepth(root.left);
int right = TreeDepth(root.right);
return Math.max(left , right) +1 ;
}
}