104. Maximum Depth of Binary Tree

本文介绍了一种使用递归实现深度优先搜索的方法来解决LeetCode上的一道关于二叉树的问题——求解二叉树的最大深度。通过具体的代码示例展示了如何从根节点开始遍历整个二叉树并计算其深度。

原题链接:https://leetcode.com/problems/maximum-depth-of-binary-tree/description/
这道题目级别为“Easy”,也确实是简单!
不废话,直接使用递归实现深度优先搜索即可:

/**
 * Created by clearbug on 2018/2/26.
 */
public class Solution {

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

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

    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);

        TreeNode rootLeft = new TreeNode(2);
        TreeNode rootRight = new TreeNode(3);
        root.left = rootLeft;
        root.right = rootRight;

        TreeNode leftLeft = new TreeNode(3);
        TreeNode leftRight = null;
        rootLeft.left = leftLeft;
        rootLeft.right = leftRight;

        TreeNode rightLeft = new TreeNode(2);
        TreeNode rightRight = null;
        rootRight.left = rightLeft;
        rootRight.right = rightRight;

        Solution s = new Solution();
        System.out.println(s.maxDepth(root));
    }

    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        return dfs(root, 1);
    }

    public int dfs(TreeNode node, int currentDepth) {

        int leftDepth = currentDepth, rightDepth = currentDepth;
        if (node.left != null) {
            leftDepth = dfs(node.left, currentDepth + 1);
        }
        if (node.right != null) {
            rightDepth = dfs(node.right, currentDepth + 1);
        }

        return leftDepth > rightDepth ?
                (leftDepth > currentDepth ? leftDepth : currentDepth) :
                (rightDepth > currentDepth ? rightDepth : currentDepth);
    }
}

转载于:https://www.cnblogs.com/optor/p/8538637.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值