leetcode记录 104. Maximum Depth of Binary Tree
来源:互联网 发布:极速淘宝秒杀器怎么用 编辑:程序博客网 时间:2024/06/05 12:01
自己思路:在深度优先遍历的时候,记录一个depth变量,如果比maxDepth变量还大,那么就替换
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { private int maxDepth; private int depth; public int maxDepth(TreeNode root) { if(root==null) return 0; else{ maxDepth = 1; depth = 0; } treeTraverse(root); return maxDepth; } private void treeTraverse(TreeNode root){ depth++; if(depth>maxDepth){ maxDepth=depth; } if(root.left!=null) treeTraverse(root.left); if(root.right!=null) treeTraverse(root.right); depth--; }}
还可以利用递归左右子树的方式,取左右子树中哪个子树深度更大(摘别人的代码):
public int maxDepth(TreeNode root){ return maxDepth(root, 0);}private int maxDepth(TreeNode node,int depth){ if(node==null) return depth; return Math.max(maxDepth(node.left,depth+1), maxDepth(node.right, depth+1));}
0 0
- leetcode记录 104. Maximum Depth of Binary Tree
- 个人记录-LeetCode 104. Maximum Depth of Binary Tree
- [LeetCode]104.Maximum Depth of Binary Tree
- 【LeetCode】104.Maximum Depth of Binary Tree
- [Leetcode] 104. Maximum Depth of Binary Tree
- LeetCode --- 104. Maximum Depth of Binary Tree
- LeetCode 104. Maximum Depth of Binary Tree
- leetCode 104. Maximum Depth of Binary Tree
- 104. Maximum Depth of Binary Tree LeetCode
- 104. Maximum Depth of Binary Tree LeetCode
- LeetCode 104. Maximum Depth of Binary Tree
- leetcode:104. Maximum Depth of Binary Tree
- LeetCode 104. Maximum Depth of Binary Tree
- [LeetCode]104. Maximum Depth of Binary Tree
- leetcode 104. Maximum Depth of Binary Tree
- LeetCode 104. Maximum Depth of Binary Tree
- 【LeetCode】104. Maximum Depth of Binary Tree
- LeetCode#104. Maximum Depth of Binary Tree
- zookeeper启动失败,zkServer.sh status 出错
- MongoDB常用命令
- linux signal 处理
- Android视图状态及重绘流程分析,带你一步步深入了解View(三)
- ios socket 实现简单的聊天系统
- leetcode记录 104. Maximum Depth of Binary Tree
- 思源黑体下载 - Google 联合 Adobe 发布免费开源优雅的设计字体 (简繁中文/日韩文)
- 一份问卷调查引发的感想
- SQL server 2014 内存表特性概述
- Android 自定义BaseAdapter
- nginx 301跳转到带www域名方法(不带www访问时重定向到带www域名)
- C++模板(一) ----函数模板
- 应避免absolute布局滥用
- MarkDown快速入门