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

下面是一个二叉树,我们需要求得第K层的节点个数。
在这里插入图片描述代码:

public class TestTree {
    static class Node {
        public char val;
        public Node left;
        public Node right;
        public Node(char val) {
            this.val = val;
            // 以下两个代码可以省略.
            // 引用类型的成员变量, 会被默认初始化为 null
            this.left = null;
            this.right = null;
        }
        @Override
    public String toString() {
            return "Node{" +
                    "val=" + val +
                    '}';
        }
    }
    // 辅助我们构造测试数据的.
    static Node build() {
        // 通过 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;
    }
    public static int kLevelSize(Node root,int k) {
        if(root==null||k<1) {
            return 0;
        }
        if(k==1) {//第一层直接返回1
            return 1;
        }
        return kLevelSize(root.left,k-1)+kLevelSize(root.right,k-1);//把A这棵树的第三层转换为B这棵树的第二层,再转换为相应的各个节点
   }
   public static void main(String[] args) {
        Node root = build();
        System.out.println(kLevelSize(root, 3));  
    }
}

运行结果
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_45755718/article/details/105643413
今日推荐