题解 | #二叉树的深度#先序遍历二叉树

二叉树的深度

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

import java.util.*;
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

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

    }

}
*/
public class Solution {

    public int TreeDepth(TreeNode root) {
        return preOrder(root, 0);
    }

    //先序遍历二叉树,根->左->右 每层+1,返回左节点和右节点最大的值即可
    public int preOrder(TreeNode root, int depth) {
        if (root == null) {
            return depth;
        }
        depth++;
        return Math.max(preOrder(root.left, depth), preOrder(root.right, depth));
    }
}

全部评论

相关推荐

强大的马里奥:不太可能,我校计算机硕士就业率99%
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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