Leetcode: Maximum Depth of Binary Tree 理解分析
来源:互联网 发布:淘宝卖家可以改名字吗 编辑:程序博客网 时间:2024/06/01 07:47
题目大意:给定一个二叉树,计算出它的深度。
理解分析:题目指出深度是从根节点到叶子节点的一条最长路径。本方法采用后序遍历法,利用节点中的val来记录该节点的最大深度。最后根节点中存放的就是该二叉树的最大深度。
实现:
/** * Definition for binary tree * 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; maxDepth(root.left); maxDepth(root.right); if(root.left == null && root.right == null) { root.val = 1; } else if(root.left != null && root.right != null) { if(root.left.val > root.right.val) root.val = root.left.val + 1; else root.val = root.right.val + 1; } else if(root.left != null) { root.val = root.left.val + 1; } else root.val = root.right.val + 1; return root.val; }}
0 0
- Leetcode: Maximum Depth of Binary Tree 理解分析
- Leetcode - Tree - Maximum Depth of Binary Tree
- [leetcode][tree] Maximum Depth of Binary Tree
- LeetCode Maximum Depth of Binary Tree
- [Leetcode] Maximum Depth of Binary Tree
- leetcode 24: Maximum Depth of Binary Tree
- [LeetCode] Maximum Depth of Binary Tree
- Leetcode 104 Maximum Depth of Binary Tree
- 【leetcode】Maximum Depth of Binary Tree
- [leetcode]Maximum Depth of Binary Tree
- [LeetCode]Maximum Depth of Binary Tree
- [leetcode]Maximum Depth of Binary Tree
- Leetcode: Maximum Depth of Binary Tree
- LeetCode-Maximum Depth of Binary Tree
- [leetcode] Maximum Depth of Binary Tree
- LeetCode - Maximum Depth of Binary Tree
- LeetCode:Maximum Depth of Binary Tree
- LeetCode | Maximum Depth of Binary Tree
- 黑马程序员——Java学习笔记之13——“反射”总结
- poj3213
- 无向图的深度优先遍历
- 浅淡C/C++中的typedef和#define
- (摘抄笔记)人脸识别经典算法二:LBP方法
- Leetcode: Maximum Depth of Binary Tree 理解分析
- Oracle几种表的简介
- OpenRisc-66-基于ORPSoC对linux进行RTL仿真
- java的注释快捷键
- 有符号整数除法指令 IDIV 汇编基础一日一学习33
- Linux的watch命令 — 实时监测命令的运行结果
- struts2自定义异常与配置
- 运行时错误检查(/RTC)编译选项及实现原理
- Lucene学习笔记