二叉树的最大深度

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例:
给定二叉树 [3,9,20,null,null,15,7]

    3
   / \
  9  20
    /  \
   15   7

返回它的最大深度 3 。

        /// <summary>
        /// 递归查找
        /// </summary>
        /// <param name="root"></param>
        /// <returns></returns>
        public static int Method1(TreeNode root)
        {
            if (root == null) return 0;
            int leftDepth = Method1(root.left);
            int rightDepth = Method1(root.right);
            return Math.Max(leftDepth, rightDepth) + 1;
        }

二叉树构造和链表有很相似的地方,递归也是常用在二叉树中的方法。核心思路就是查找每一个节点下的左右子节点是否存在,若有则就和兄弟节点进行比较找出较大的存在(深度不是从0开始)。

二叉树

猜你喜欢

转载自blog.csdn.net/u012371712/article/details/81076617