数据结构-二叉树(统计二叉树的结点个数递归与非递归算法)

文章目录

思路

求结点个数为什么能用递归?

二叉树求结点个数,从根结点开始,求二叉树结点个数,对于根结点就是求左右子树所有结点数之和再加一,对于左右子树又是如此计算,这样的形式满足递归的思想,大问题化小问题,小问题有一个最终的出口,出口就是最下面那个结点左右子树为空,这样空节点的结点个数为 0

如何用栈来思考二叉树结点个数?

就是二叉树的遍历,先序中序后序,层次遍历皆可以,栈中的数据是从没有到不断存入,到最后栈为空,所以我们可以在 push 后让结点 count 加一,或者在 pop 时候让结点 count 加一都可以,下面例子我才用中序遍历的非递归算法,然后 push 时加一来处理

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 BinaryTree(int[] arr) {
        root = new Node();
        this.arr_in = arr;
        arr_out = new int[arr.length];
        index = 0;
    }
    
    // 得到二叉树结点的个数(递归)
    public int getNodesNumber(Node r) {
        if (r)
            return getNodesNumber(r.left) + getNodesNumber(r.right) + 1;
        else
            return 0;
    }
    
    // 得到二叉树结点的个数(非递归)
    public int getNodesNumber(Node r) {
        Stack stack = new Stack();
        Node node = r;
        int count = 0;
        if (node) {
            stack.push(node);
            count++;
            node = node.left
        }
        else {
            Node top = stack.pop();
            node = top.right;
        }
        return count;
    }
    
发布了197 篇原创文章 · 获赞 62 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/abcnull/article/details/104462505