求二叉树叶子节点的个数

tag: 二叉树

 

思路:

(1)通过先序遍历的方式求解

(2)叶子节点的特点: 左右孩子都为空

 

也可以用递归方式

 

package com.zhaochao.tree;

import java.util.Stack;

/**
 * Created by zhaochao on 17/1/23.
 * 叶子结点的特点: 左右孩子都为空
 * 通过先序的方式找到叶子结点
 *
 */
public class LeafNumber {

    int flag = 0;

    public int getCountsOfLeaves(TreeNode root) {
        int count = 0;
        if(root == null) {
            return count;
        }
        Stack<TreeNode> stack = new Stack<TreeNode>();
        stack.push(root);
        while(!stack.isEmpty()) {
            TreeNode node = stack.pop();
            if(node.left == null && node.right == null) {
                count++;
            }
            if(node.right != null) {
                stack.push(node.right);
            }
            if(node.left != null) {
                stack.push(node.left);
            }
        }
        return count;
    }

    //递归求解
    public void getCountRec(TreeNode root) {
        if(root == null) {
            return;
        }
        if(root.left == null && root.right == null) {
            flag++;
        }
        getCountRec(root.left);
        getCountRec(root.right);
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(0);
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);
        TreeNode node4 = new TreeNode(4);

        root.left = node1;
        root.right = node2;
        node2.left = node3;
        node2.right = node4;

        LeafNumber test = new LeafNumber();
        int count = 0;
        count = test.getCountsOfLeaves(root);

        System.out.println("The number of nodes in the tree is " + count);

        test.getCountRec(root);
        System.out.println("Recursion : the number of nodes in the tree is " + test.flag);


    }


}

  

  

转载于:https://www.cnblogs.com/superzhaochao/p/6346874.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值