Data Structure - Tree - Get number of nodes (Java language)

Detailed code visible github:

https://github.com/AbitGo/myClassWork/tree/master/workspace_ds

 Three implementation methods are recursive, non-recursive, as well as the use of similar level traversal algorithm.

 

Detailed code implementation:

//统计二叉树中结点个数的算法
    //使用递归的方式
    public int countNode1(BiTreeNode t) {
        //使用递归算法
        int count = 0;
        if (t != null) {
            ++count;
            count += countNode1(t.lchild);
            count += countNode1(t.rchild);
        }
        return count;
    }

    //统计二叉树中结点个数的算法
    //使用递归的方式
    public int countNode2(BiTreeNode t) {
        //使用递归算法
        if (t == null) {
            return 0;
        } else {
            return 1 + countNode2(t.lchild) + countNode2(t.rchild);
        }
    }

    //统计二叉树中结点个数的算法
    //使用非递归的方式
    //类似于层次历遍
    public int countNode3(BiTreeNode t) {
        //使用递归算法
        int count = 0;
        if (t != null) {
            LinkSqeue linkSqeue = new LinkSqeue();
            linkSqeue.offer(t);
            while (!linkSqeue.isEmpty()) {
                t = (BiTreeNode) linkSqeue.poll();
                ++count;
                if (t.lchild != null) {
                    linkSqeue.offer(t.lchild);
                }
                if (t.rchild != null) {
                    linkSqeue.offer(t.rchild);
                }
            }
        }
        return count;
    }

 

Published 84 original articles · won praise 39 · views 90000 +

Guess you like

Origin blog.csdn.net/Abit_Go/article/details/104163049