-
class Solution { public int maxDepth(TreeNode root) { return root == null ? 0 : Math.max(maxDepth(root.left), maxDepth(root.right)) + 1; } }
尝试了半天深度搜索遍历方法(广度搜索遍历就很简单了),都不成功…所以偷个懒,写一个递归放上来吧!
2.Minimum Depth of Binary Tree
class Solution {
public int minDepth(TreeNode root) {
if(root == null) return 0;
if(root.left == null && root.right == null) return 1;
int left = minDepth(root.left);
int right = minDepth(root.right);
return root.left == null || root.right == null ? left + right + 1 : Math.min(left,right) + 1;
}
}
这个算法必须掌握!通过看最左和最右边level数量是否相等,来判断是否为完全二叉树。如果是,那么直接乘方就能知道个数啦!如果不是,只能一个一个数(最后一行return)。
class Solution {
public int countNodes(TreeNode root) {
if(root == null) return 0;
int leftCount = 1, rightCount = 1;
TreeNode tmpl = root, tmpr = root;
while(tmpl.left != null){
tmpl = tmpl.left;
++leftCount;
}
while(tmpr.right != null){
tmpr = tmpr.right;
++rightCount;
}
if(leftCount == rightCount){
return (int) Math.pow(2, leftCount) - 1;
}
return 1 + countNodes(root.left) + countNodes(root.right);
}
}
本文介绍了解决二叉树最大深度、最小深度及完全二叉树节点计数的问题,通过递归方法实现了这三种算法。针对完全二叉树节点计数问题,提出了一种高效算法,通过检查最左侧和最右侧子树高度来判断是否为完全二叉树。
1130

被折叠的 条评论
为什么被折叠?



