这题比较简单,简单的递归下就完事了,难怪排AC第二高的,感觉比AC第一高的容易多了
public int maxDepth(TreeNode root){
if(root==null)
return 0;
int result=FindDepth(root,1);
return result;
}
public static int FindDepth(TreeNode root,int deep){
int a=0,b=0;
if(root.left==null && root.right==null)
return deep;
else {
if (root.left!=null)
a = FindDepth(root.left,deep+1);
if(root.right!=null)
b = FindDepth(root.right,deep+1);
return a>b?a:b;
}
}
完事去discuss上看了下,首先自己写的代码一点都不简洁,看看别人的,很汗颜。。
public int maxDepth(TreeNode root) {
if(root == null)
return 0;
return Math.max(maxDepth(root.left),maxDepth(root.right))+1;
}
其次关于写的这个算法的时间复杂度,看了discuss上一位哥们的描述,貌似是这样,不过还有待研究.
The complexity is exactly O(n). The recursion would touch every node in the tree, for once. The function wont return until it does so.
最后研究了下discuss上一位现成的不用递归实现的算法,准备晚上回去好好看看(队列什么的完全不用用的...巨汗..)
/**
* 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;
Queue<TreeNode> q = new Queue<TreeNode>();
q.enQ(root);
q.last = root;
int depth = 0;
while(q.count > 0){
TreeNode p = q.deQ();
if(p.left != null)q.enQ(p.left);
if(p.right != null)q.enQ(p.right);
if(q.last == p){
// current node is the last one on that depth
depth++;
if(q.tail != null)
q.last = q.tail.val;
}
}
return depth;
}
public class Queue<T> {
QueueNode<T> head = null, tail = null;
T last = null;
int count = 0;
public void enQ(T t){
QueueNode<T> n = new QueueNode<T>(t);
if(this.count == 0){ // pay much attention to head & tail of Queue
this.tail = n;
this.head = n;
}else{
this.tail.next = n;
this.tail = n;
}
this.count++;
}
public T deQ(){
if(this.count==0)return null;
T tmp = this.head.val;
if(head == tail){
// deQ last elem, reset head & tail
head = null;
tail = null;
}else{
this.head = this.head.next;
}
this.count--;
return tmp;
}
}
public class QueueNode<T> {
T val;
QueueNode<T> next;
public QueueNode(T t){
this.val = t;
}
}
}
我写的非递归
public static int FindDepth2(TreeNode root){
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
int eachNum = 1,result=0;
int j=0;
while(!queue.isEmpty()){
result++;
j = 0;
for(int i=1;i<=eachNum;i++){
TreeNode top=queue.poll();
if(top.left!=null){
queue.add(top.left);
j++;
}
if(top.right!=null){
queue.add(top.right);
j++;
}
}
eachNum=j;
}
return result;
}