求二叉树节点个数(递归)

下面有一个二叉树,求其节点个数。
分析:
想要得到二叉树的节点个数,我们可以递归遍历这个二叉树,当一个树的根节点不为null时,对其计数。
《求二叉树节点个数(递归)》
我在下面得代码里写了两种方法,一种是借助成员变量,一种是直接递归计数。
代码:

public class TestTree1 { 
    static class Node { 
        public char val;
        public Node left;
        public Node right;
        public Node(char val) { 
            this.val = val;
            this.left = null;
            this.right = null;
        }
    }
    static Node build() { 
        Node A = new Node('A');
        Node B = new Node('B');
        Node C = new Node('C');
        Node D = new Node('D');
        Node E = new Node('E');
        Node F = new Node('F');
        Node G = new Node('G');
        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.left = F;
        C.right = G;
        return A;
    }
    static int TreeSize = 0;
    static void Size(Node root) { 
        if (root == null) { 
            return;
        }
        TreeSize++;
        Size(root.left);
        Size(root.right);
    }
    static int TreeSize(Node root) { 
        if(root==null) { 
            return 0;
        }
        return 1+ TreeSize(root.left)+TreeSize(root.right);
    }
    public static void main(String[] args) { 
        Node root = build();
        Size(root);
        System.out.println(TreeSize);
       Node root1 = build();
        System.out.println(TreeSize(root1));
    }
}

运行结果:
《求二叉树节点个数(递归)》

    原文作者:郑兽兽
    原文地址: https://blog.csdn.net/weixin_45755718/article/details/105622261
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞