統計二叉樹葉子結點數目
葉子結點:就是它的左右孩子都為空的結點稱為葉子結點。
思路:遞歸遍歷二叉樹
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); } }