统计二叉树叶子结点数目
叶子结点:就是它的左右孩子都为空的结点称为叶子结点。
思路:递归遍历二叉树
1、如果当前结点为空,就返回0;
2、如果它的左孩子和右孩子为空就说明它是叶子结点,返回1
3、如果条件2不满足就说明它有孩子结点,继续递归调用,分为左右孩子去调用。
代码如下:
public class TreeLeafCount { /** * 定义一个内部类TreeNode */
class TreeNode{ TreeNode left; TreeNode right; char val; public TreeNode(char val){ this.val = val; } } public static int leafCount(TreeNode tree){ if(tree == null) return 0; if(tree.left == null && tree.right == null) return 1; return leafCount(tree.left) + leafCount(tree.right); } }