leetcode — maximum-depth-of-binary-tree

本文介绍了一种求解二叉树最大深度的方法,通过深度优先搜索遍历二叉树节点,递归地计算左右子树的最大深度,并返回两者中较大者加一作为当前节点的最大深度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
 *
 * Source : https://oj.leetcode.com/problems/maximum-depth-of-binary-tree/
 *
 *
 *
 * Given a binary tree, find its maximum depth.
 *
 * The maximum depth is the number of nodes along the longest path from the root node
 * down to the farthest leaf node.
 */
public class MaxDepthOfBinaryTree {


    /**
     * 求出二叉树树的深度,使用深度优先
     *
     * @param root
     * @return
     */
    public int maxDepth (TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftMax = 1;
        int rightMax = 1;
        leftMax += maxDepth(root.leftChild);
        rightMax += maxDepth(root.rightChild);

        return Math.max(leftMax, rightMax);
    }


    public TreeNode createTree (char[] treeArr) {
        TreeNode[] tree = new TreeNode[treeArr.length];
        for (int i = 0; i < treeArr.length; i++) {
            if (treeArr[i] == '#') {
                tree[i] = null;
                continue;
            }
            tree[i] = new TreeNode(treeArr[i]-'0');
        }
        int pos = 0;
        for (int i = 0; i < treeArr.length && pos < treeArr.length-1; i++) {
            if (tree[i] != null) {
                tree[i].leftChild = tree[++pos];
                if (pos < treeArr.length-1) {
                    tree[i].rightChild = tree[++pos];
                }
            }
        }
        return tree[0];
    }

    private class TreeNode {
        TreeNode leftChild;
        TreeNode rightChild;
        int value;

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

        public TreeNode() {

        }
    }

    public static void main(String[] args) {
        MaxDepthOfBinaryTree depthOfBinaryTree = new MaxDepthOfBinaryTree();
        char[] arr = new char[]{'3','9','2','#','#','1','7'};

        System.out.println(depthOfBinaryTree.maxDepth(depthOfBinaryTree.createTree(arr)));
    }
}

转载于:https://www.cnblogs.com/sunshine-2015/p/7807079.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值