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

文章目录

思路

思路上也没啥的,和求二叉树结点个数或者说求二叉树叶子结点个数思路很像,博主的前几篇博文有讲

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 getNonleafCountRecursion(Node r) {
        // 左右两个结点都是 null,此结点必为叶子
        if (r.left == null && r.right == null)
            return 0;
        else
            return getNonleafCount(r.left) + getNonleafCount(r.right) + 1;
    }
    
    // 得到二叉树非叶子结点的个数(非递归)
    public int getNonleafCount(Node r) {
        Stack stack = new Stack();
        Node node = r;
        int nonleaf = 0;
        while (node || !stack.empty()) {
            if (node.left != null || node.right != null) {
                stack.push(node);
                nonleaf++;
                node = node.left;
            }
            else
                node = stack.pop().right;
        }
        return nonleaf;
    }
发布了197 篇原创文章 · 获赞 62 · 访问量 7万+

猜你喜欢

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