题解 | #二叉树的深度#

二叉树的深度

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;
    }
}
全部评论

相关推荐

程序员小白条:找的太晚,别人都是大三实习,然后大四秋招春招的,你大四下了才去实习,晚1年
点赞 评论 收藏
分享
苍蓝星上艾露:这简历。。。可以试试我写的开源简历优化工具https://github.com/weicanie/prisma-ai
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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