104. Maximum Depth of Binary Tree

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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容