1 题目链接
https://www.nowcoder.com/exam/oj/ta?page=1&tpId=13&type=13
2 题目
3 思路 & 答案
原问题:求二叉树的深度
将原问题拆解,原问题 = Max(根节点的左子树的深度,根节点的右子树的深度) + 1
…
不断地将问题进行拆解,直到叶子节点成为问题的根节点,返回1即可。
public class Solution {
public int TreeDepth(TreeNode root) {
if (root == null) {
return 0;
}
return Math.max(TreeDepth(root.left), TreeDepth(root.right)) + 1;
}
}
上面这个代码,在遇到叶子节点时还会继续调用TreeDepth方法,然后,叶子结点的左孩子和右孩子都为空,最后得到,叶子节点的深度为1。可以在上面的代码上再加上一个if判断语句,判断如果是叶子节点,直接返回1,省去判断其左孩子和右孩子是否为空。
public class Solution {
public int TreeDepth(TreeNode root) {
if (root == null) {
return 0;
}
if (root.left == null && root.right == null) {
return 1;
}
return Math.max(TreeDepth(root.left), TreeDepth(root.right)) + 1;
}
}
4 测试程序 & 运行结果
下面这个测试程序可以更直观的感受递归执行的过程
import org.junit.Test;
import java.util.*;
public class Solution {
@Test
public void test() {
TreeNode t1 = new TreeNode(1);
TreeNode t2 = new TreeNode(2);
TreeNode t3 = new TreeNode(3);
TreeNode t4 = new TreeNode(4);
TreeNode t5 = new TreeNode(5);
TreeNode t6 = new TreeNode(6);
TreeNode t7 = new TreeNode(7);
t1.left = t2;
t1.right = t3;
t2.left = t4;
t2.right = t5;
t5.left = t7;
t3.right = t6;
int depth = TreeDepth(t1);
System.out.println("这棵树的深度是:" + depth);
}
public int TreeDepth(TreeNode root) {
if (root == null) {
return 0;
}
int res = Math.max(TreeDepth(root.left), TreeDepth(root.right)) + 1;
System.out.println("当前节点 " + root.val + ":" + res);
return res;
}
}
运行结果
当前节点 4:1
当前节点 7:1
当前节点 5:2
当前节点 2:3
当前节点 6:1
当前节点 3:2
当前节点 1:4
这棵树的深度是:4