LeetCode 104. Maximum Depth of Binary Tree
2016-02-11 16:34
411 查看
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.
本题目是简单的二叉树深度问题,二叉树是每个节点最多有两个子树的树结构,二叉树还有递归定义:
二叉树是n(n>=0)个有限结点构成的集合。N=0称为空二叉树;n>0的二叉树由一个根结点和两互不相交的,分别称为左子树和右子树的二叉树构成。
二叉树中任何结点的第1个子树称为其左子树,左子树的根称为该结点的左孩子;二叉树中任何结点的第2个子树称为其右子树,左子树的根称为该结点的右孩子。
更多二叉树的性质和实现:见luoweifu的博客 二叉树(1)——二叉树的定义和递归实现
利用递归求二叉树的最大深度:
简单解释:将每个结点都看做根节点,如果结点为空,则返回0,此为递归的出口,如果不为空,则深度至少为1,分别求其左子树和右子树的深度,进行比较,即可求出最大深度。
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
本题目是简单的二叉树深度问题,二叉树是每个节点最多有两个子树的树结构,二叉树还有递归定义:
二叉树是n(n>=0)个有限结点构成的集合。N=0称为空二叉树;n>0的二叉树由一个根结点和两互不相交的,分别称为左子树和右子树的二叉树构成。
二叉树中任何结点的第1个子树称为其左子树,左子树的根称为该结点的左孩子;二叉树中任何结点的第2个子树称为其右子树,左子树的根称为该结点的右孩子。
更多二叉树的性质和实现:见luoweifu的博客 二叉树(1)——二叉树的定义和递归实现
利用递归求二叉树的最大深度:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public int maxDepth(TreeNode root) { if(root == null){ return 0; } int leftMaxDepth = maxDepth(root.left); int rightMaxDepth = maxDepth(root.right); return 1 + Math.max(leftMaxDepth,rightMaxDepth); } }
简单解释:将每个结点都看做根节点,如果结点为空,则返回0,此为递归的出口,如果不为空,则深度至少为1,分别求其左子树和右子树的深度,进行比较,即可求出最大深度。
相关文章推荐
- R语言之内存管理
- git rebase与 git合并(error: failed to push some refs to)解决方法
- 游戏的定价
- hdu 5339 Untitled【dfs过】
- 计算机图形学入门教程OpenGL版.第1篇.基本概念
- 心灵指南 刘墉 第二辑 创造自己 笔记
- 使用ultraEdit拷贝二进制文件内容时的异常
- 【NOIP2015】信息传递
- Xcode下写入、读取文件
- HDOJ 1050 Moving Tables
- HDU2456(01背包变形)
- 网页调试技巧:抓取马上跳转的页面POST信息或者页面内容
- Nginx 开启 path_info功能
- iOS-XML文档解析(NSXMLParser)
- windowbuilde02 表格创建
- 继KB3035583后微软再发恶意补丁KB3123862、千万不要打!!!
- node stream api的应用,断电续传与秒传的例子
- java volatile详解(转)
- 微软推送Win10 Mobile技术预览版10586.107 Win10 Mobile预览版10586.107更新内容汇总
- GetMemory函数的几种经典考法