LeetCode104 二叉树的最大深度
public class code104 {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
int leftheight = maxDepth(root.left);
int rightheight = maxDepth(root.right);
return 1 + Math.max(leftheight, rightheight);
}
}
遍历顺序为后序遍历,实际上求的是根节点的高度,同时也是二叉树的最大深度
LeetCode111 二叉树的最小深度
public class code111 {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
if (root.left == null && root.right != null) {
return 1 + minDepth(root.right);
}
if (root.left != null && root.right == null) {
return 1 + minDepth(root.left);
}
return 1 + Math.min(minDepth(root.left), minDepth(root.right));
}
}
注意如果有孩子为空节点的话,要特殊处理一下
LeetCode222 完全二叉树的节点个数
public class code222 {
public int countNodes(TreeNode root) {
if (root == null) {
return 0;
}
return 1 + countNodes(root.left) + countNodes(root.right);
}
}