下面是一个二叉树,我们需要编写代码求其的叶子节点个数。
分析:一个树的左子树和右子树都为null就是叶子节点,我们需要对每个数进行判断,依次遍历,遇到满足条件的进行计数即可。
我在下面用了两种方法,其中一种是借助静态成员变量
代码:
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;
}
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 leafSize = 0;//借助静态成员变量
static void LeafSzie(Node root){
if(root==null) {
return;
}
if(root.left==null&&root.right==null) {
leafSize++;
return;
}
LeafSzie(root.left);
LeafSzie(root.right);
}
public static int LeafSize(Node root){
if(root==null) {
return 0;
}
if(root.left==null&&root.right==null) {
return 1;
}
return LeafSize(root.left)+LeafSize(root.right);
}
public static void main(String[] args) {
Node root = build();
LeafSzie(root);
System.out.println(leafSize);
Node root1 = build();
System.out.println(LeafSize(root1));
}
}
运行结果: