怎么输出所有叶子结点。
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); } }本回答被题主选为最佳回答 , 对您是否有帮助呢?评论 打赏 举报解决 1无用