题解 | #二叉树的深度#

二叉树的深度

http://www.nowcoder.com/practice/435fb86331474282a3499955f0a41e8b

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
import java.util.*;
public class Solution {
    /**********************************************************************************/
    // 非递归方式
    /*
    public int TreeDepth(TreeNode root) {
        if (null == root) {
            return 0;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        TreeNode node = root;
        HashMap<TreeNode, Integer> hashMap = new HashMap<>();
        int res = 0;
        queue.add(node);
        hashMap.put(node, 1);
        while (!queue.isEmpty()) {
            node = queue.poll();
            int currentLevel = hashMap.get(node);
            res = Math.max(res, currentLevel);
            if (null != node.left) {
                queue.add(node.left);
                hashMap.put(node.left, currentLevel + 1);
            }
            if (null != node.right) {
                queue.add(node.right);
                hashMap.put(node.right, currentLevel + 1);
            }
        }
        return res;
    }
    */
    
    /**********************************************************************************/
    // 递归方式
    public int TreeDepth(TreeNode root) {
        if (null == root) {
            return 0;
        }
        if (null == root.left && null == root.right) {
            return 1;
        }
        return Math.max(TreeDepth(root.left), TreeDepth(root.right)) + 1;
    }
}
全部评论

相关推荐

03-02 08:18
集美大学 Java
钱嘛数字而已:没有赛事奖项么?另外,项目经历字有点多哈,建议突出一下重点:用的什么技术,解决什么问题,达到什么效果。
大家都开始春招面试了吗
点赞 评论 收藏
分享
03-31 14:46
已编辑
门头沟学院 Web前端
励志成为双港第一ja...:这其实很正常,离的太远了,他认为你不会来,就为了混个面试,而且成本很高,实习生都优先选本地高校。吃了地域的亏,所有很多时候地域可能比院校层次更重要。
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务