树的结构为
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x)
{
val = x;
}
}
二叉树中叶子节点的个数
叶子指没有两个孩子的节点。递归的方法是,一个节点下的叶子节点数目等于其左子树和右子树叶子节点数目之和
public int leavesNum(TreeNode root) {
if(root == null) return 0;
else if(root.left == null && root.right == null) return 1;
else return leavesNum(root.left)+leavesNum(root.right);
}
二叉树第K层节点数目
从根结点向下第k层的节点数,应该等于根左右孩子向下k-1层的节点数之和。递归不断向下。
public int nodesNum(TreeNode root, int k) {
if(root == null) return 0;
if(k == 1) return 1;
return nodesNum(root.left, k-1) + nodesNum(root.right, k-1);
}
二叉树最大高度
https://leetcode.com/problems/maximum-depth-of-binary-tree/
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
最大高度就是指树的高度:树的高度应该为其左子树和右子树的最大高度+1
public int maxDepth(TreeNode root) {
if(root == null) return 0;
else{
int leftmax = maxDepth(root.left), rightmax = maxDepth(root.right);
return leftmax > rightmax ? (leftmax+1) : (rightmax+1);
}
}
二叉树最小高度
https://leetcode.com/problems/minimum-depth-of-binary-tree/
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node
二叉树最小高度并不仅仅是上一道题的相反逻辑,注意,最大高度直接递归可以保证是从根到叶子节点,但是最小高度用这种逻辑递归并不能保证是到叶子节点(可能会是从根到某个只有一个孩子的节点)
public int minDepth(TreeNode root) {
if(root == null) return 0;
else{
int leftmin = minDepth(root.left), rightmin = minDepth(root.right);
if(leftmin == 0) return rightmin+1;
if(rightmin == 0) return leftmin+1;
else return leftmin < rightmin ? leftmin+1 : rightmin+1;
}
}