1 计算二叉树深度
非递归实现
public int nonRecursive(TreeNode root){
if(root == null)
return 0;
Queue<TreeNode> queue = new ArrayList<>();
queue.add(root);
int depth = 0, count = 0, nextLayerCount = 1;
while (queue.size() != 0){
TreeNode top = queue.poll();
count ++;
if(top.left != null)
queue.add(top.left);
if(top.right != null)
queue.add(top.right);
if(count == nextLayerCount){
nextLayerCount = queue.size();
count = 0;
depth++;
}
}
return depth;
}
递归实现
public int recursive(TreeNode node){
if(root == null)
return 0;
int leftDepth = recursive(root.left);
int rightDepth = recursiove(root.right);
return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1;
}
完整版:
public class TreeDepth {
public int NonRecursive(TreeNode root) {
if (root == null)
return 0;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
// depth 当前节点所在层数
// count 在当前层已经遍历的节点数
// nextCount 下层节点的数量
int depth = 0, count = 0, nextCount = 1;
// 队列非空
while (queue.size() != 0) {
// 取出队首节点
TreeNode top = queue.poll();
count++;
if (top.left != null)
queue.add(top.left);
if (top.right != null)
queue.add(top.right);
// 本层节点遍历结束
if (count == nextCount) {
nextCount = queue.size();
count = 0;
depth++;
}
}
return depth;
}
public int Recursive(TreeNode root) {
if (root == null)
return 0;
int left = Recursive(root.left);
int right = Recursive(root.right);
return left > right ? left + 1 : right + 1;
}
}
2 判断是否为平衡二叉树
public boolean isBalanced = true;
public boolean isBalancedTree(TreeNode root){
getDepth(root);
return isBalanced;
}
public int getDepth(TreeNode node){
if ( node == null ){
return 0;
int left = getDepth(node.left);
int right = getDepth(node.right);
if(Math.abs(left - right) > 1){
isBalanced = false;
return 0;
}
return left > right : left + 1 : right + 1 ;
}