104. Maximum Depth of Binary Tree
Link
難易度 : Easy
依照對岸Carl大神的練習順序,接下來會連做10題類似觀念的題目,題號如下 :
- 102.二叉树的层序遍历
- 107.二叉树的层次遍历II
- 199.二叉树的右视图
- 637.二叉树的层平均值
- 429.N叉树的层序遍历
- 515.在每个树行中找最大值
- 116.填充每个节点的下一个右侧节点指针
- 117.填充每个节点的下一个右侧节点指针II
- 104.二叉树的最大深度
- 111.二叉树的最小深度
那麼就直接開始吧!!!
題目要求找出binary tree的最大深度,先使用模板來解題吧!
class Solution
{
public int maxDepth(TreeNode root)
{
Queue<TreeNode> queue = new LinkedList<TreeNode>();
TreeNode current;
int depth=0;
if(root==null)
{
return depth;
}
queue.add(root);
while(!queue.isEmpty())
{
int size = queue.size();
depth++;
//遍尋此層數量的所有node 之後加入的不與理會
for(int i=0;i<size;i++)
{
current = queue.poll();
if(current.left!=null)
{
queue.add(current.left);
}
if(current.right!=null)
{
queue.add(current.right);
}
}
}
return depth;
}
}
但是同樣的看得出來,效率很差勁,因此看了一下discuss的做法,直接用簡單的recursive來做就可以快得非常多!
code非常簡單,應該很容易就能看懂
class Solution
{
public int maxDepth(TreeNode root)
{
if(root==null)
{
return 0;
}
return 1+(Math.max(maxDepth(root.left), maxDepth(root.right)));
}
}