m0_59247291 2021-12-15 12:42 采纳率: 100%
浏览 94
已结题

求二又树的叶子结点的个数,并打印输出所有叶子结点.

怎么输出所有叶子结点。

  • 写回答

5条回答 默认 最新

  • CSDN专家-sinJack 2021-12-15 13:45
    关注
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) {
            val = x;
        }
        public static void main(String[] args) {
            Solution tree = new Solution();
            TreeNode root = new TreeNode(3);
            root.left = new TreeNode(9);
            root.right = new TreeNode(20);
            root.right.left = new TreeNode(15);
            root.right.right = new TreeNode(7);
            System.out.println("叶子节点总数:"+tree.getLeafCount(root));
        }
    }
    class Solution {
        public int getLeafCount(TreeNode root) {
            if (root == null) {
                return 0;
            }
            if (root.left == null && root.right == null) {
                // 输出叶子节点
                System.out.println("叶子节点:" + root.val);
                return 1;
            }
            return getLeafCount(root.left) + getLeafCount(root.right);
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

问题事件

  • 系统已结题 12月24日
  • 已采纳回答 12月16日
  • 创建了问题 12月15日