https://www.nowcoder.com/practice/435fb86331474282a3499955f0a41e8b?tpId=13&tqId=11191&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
| 日期 | 是否一次通过 | comment |
|----|----|----|
|2019-01-26 13:20|Y||
|2019-01-27 13:20|N|对helper中的递归理解不够深刻|
题目:输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
1. 递归
public class Solution {
public int TreeDepth(TreeNode root) {
if(root == null) {
return 0;
}
TreeNode nodeD = new TreeNode(0);
helper(nodeD, root);
return nodeD.val + 1;
}
private int helper(TreeNode nodeD, TreeNode root) {
if(root == null) {
return 0;
}
int leftD = helper(nodeD, root.left);
int rightD = helper(nodeD, root.right);
nodeD.val = Math.max(Math.max(leftD, rightD), nodeD.val);
return Math.max(leftD, rightD) + 1;
}
}
2.递归
public class Solution {
public int TreeDepth(TreeNode root) {
if(root == null) {
return 0;
}
int leftDpt = TreeDepth(root.left);
int rightDpt = TreeDepth(root.right);
return Math.max(leftDpt, rightDpt) + 1;
}
}