数据结构-二叉树(求二叉树叶子节点数的递归和非递归算法)

文章目录

思路

思路这一块没啥可说,递归主要是求左子树叶子结点数+求右子树叶子结点数,递归实现。非递归就是用到了栈,一个结点一个结点的保存,保存到叶子结点时候,就让叶子出栈,计数+1,然后让栈顶指向右结点再入栈循环执行即可

Java 实现

// 结点
class Node {
    int data;
    Node left = null;
    Node right = null;
}

// 二叉树
public class BinaryTree {
    // 根结点
    private Node root;
    // 输入的数组
    private int[] arr_in;
    // 输出的数组
    private int[] arr_out;
    // 记录数组下标
    private static int index;

// 得到二叉树叶子结点的个数(递归)
    public int getLeafCountRecursion(Node r) {
        if (r.left == null && r.right == null)
            return 1;
        else
        	return getLeafCountRecursion(r.left) + getLeafCountRecursion(r.right);
    }
    
    // 得到二叉树叶子结点的个数(非递归)
    public int getLeafCount(Node r) {
        Stack stack = new Stack();
        Node node = r;
        int count = 0;
        while (node || !stack.empty()) {
        	if (node) {
				if (node.left != null || node.right != null) {
					// 只存中间结点,不存叶子结点
                	stack.push(node);
                	node = node.left;
            	}
            	else {
                	count++;
                	node = stack.pop().right;
            	}
			}
            else {
            	if (stack.peek().right)
					node = stack.pop().right;
				else {
					stack.pop();
					node = stack.pop().right;
				}
			}        
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

abcnull

您的打赏是我创作的动力之一

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值