题目:求二叉树叶子节点的个数
思路:递归和迭代
递归:求叶子节点的个数,就是求 左子树叶子节点的个数 加上 右子树叶子节点的个数
public static int numberOfLeaf(TreeNode root){ if(root == null) return 0; if(root.left == null && root.right == null) return 1; return numberOfLeaf(root.left)+numberOfLeaf(root.right);}
迭代:
public static int numberOfLeaves(TreeNode root){ if(root == null) return 0; if(root.left == null && root.right == null) return 1; Queuequeue = new LinkedList (); queue.add(root); int leafNodes = 0; while(!queue.isEmpty()){ TreeNode cur = queue.remove(); if(cur.left != null){ queue.add(cur.left); } if(cur.right != null){ queue.add(cur.right); } if(cur.left == null && cur.right == null){ leafNodes++; } } return leafNodes; }