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

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

怎么输出所有叶子结点。

  • 写回答

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日

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度