您的位置:首页 > 理论基础 > 数据结构算法

数据结构之求二叉树的所有叶子和以及叶子总数

2017-06-11 22:14 225 查看

1、题目

数据结构之求二叉树的所有叶子和以及叶子总数

2、代码实现

tree.java
package leetcode.chenyu.test;

public class Tree {
int val;
Tree left;
Tree right;
Tree(int val) {
this.val = val;
}
}


package leetcode.chenyu.test;

public class TreeTest {
public static int sum = 0;
public static int count = 0;
public static void main(String[] args) {
Tree t1 = new Tree(1);
Tree t2 = new Tree(2);
Tree t3 = new Tree(3);
Tree t4 = new Tree(4);
Tree t5 = new Tree(5);
t1.left = t2;
t1.right= t3;
t2.left = t4;
t3.left = t5;
lastPrintf(t1);
System.out.println("sum is" + sum + "count is " + count);

}
public static void lastPrintf(Tree head) {
if (head == null)
return;
boolean boo = false;
lastPrintf(head.left);
lastPrintf(head.right);
if (head.left == null && head.right == null)
boo = true;
if (boo) {
sum += head.val;
count++;
}
}
}


3、运行结果

sum is9 count is 2
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐