根节点的高度
= 最大深度 ( 后序遍历 )
104.二叉树的最大深度
public int maxDepth(TreeNode root) {
return getDepth(root);
}
public int getDepth(TreeNode cur) {
if (cur == null) return 0;
int leftDepth = getDepth(cur.left);
int rightDepth = getDepth(cur.right);
return 1 + Math.max(leftDepth, rightDepth);
}
//通过队列做
public int maxDepthByDeque(Node root) {
Deque<Node> deque = new LinkedList<>();
if (root == null) return 0;
deque.offerLast(root);
Node cur;
int depth = 0;
while (!deque.isEmpty()) {
int len = deque.size();
while (len > 0) {
cur = deque.pollFirst();
for (Node child : cur.children) {
deque.offerLast(child);
}
len--;
}
depth++;
}
return depth;
}
111.二叉树的最小深度
public int minDepth(TreeNode root) {
return getMinDepth(root);
}
public int getMinDepth(TreeNode cur) {
if (cur == null) {
return 0;
}
// 下面可以简化,很简单,吧leftDepth换成对应的函数
// 为了看动,不简化.
int leftDepth = getMinDepth(cur.left);
int rightDepth = getMinDepth(cur.right);
if (cur.right == null && cur.left != null) {
return 1 + leftDepth;
}
if (cur.left == null && cur.right != null) {
return 1 + rightDepth;
}
return 1 + Math.min(leftDepth, rightDepth);
}
222. 完全二叉树的节点个数
public int countNodes(TreeNode root) {
if (root == null) {
return 0;
}
// 加入下面这一整块,就是为了利用完全二叉树的性质 -> 完全二叉树节点数: 2^n-1(n=depth)
// TreeNode leftTree = root, rightTree = root;
// int rightDepth = 0, leftDepth = 0;
// while (rightTree.right != null) {
// rightDepth++;
// rightTree = rightTree.right;
// }
// while (leftTree.left != null) {
// leftDepth++;
// leftTree = leftTree.left;
// }
// if (leftDepth == rightDepth) {
// return 1 << leftDepth + 1;
// }
// 上面注释全部删除,或者全部加入,都可以运行成功
int right = countNodes(root.right);
int left = countNodes(root.left);
return left + right + 1;
}
标签:return,cur,int,leftDepth,高度,二叉树,深度,null,root
From: https://www.cnblogs.com/Chain-Tian/p/17007114.html