輸入一棵二叉樹,求該樹的深度。從根結點到葉結點依次通過的結點(含根、葉結點)造成樹的一條路徑,最長路徑的長度爲樹的深度。

//方案一:java

public class Solution {code

int max=0;

int temp=0;

public int TreeDepth(TreeNode root) {

   f(root);
    return max;
}

public void f(TreeNode root){

    if(root==null){
        if(temp>max)
            max=temp;
        return;
    }
   
    temp++;
    f(root.left);
    f(root.right);
     temp--;
    
    
}

}遞歸

//方案二:rem

public class Solution {io

public int TreeDepth(TreeNode root) {

  if(root==null)
  
      return 0;
	  
    return (1+TreeDepth(root.left))>(1+TreeDepth(root.right))?(1+TreeDepth(root.left)):(1+TreeDepth(root.right));
}

}class

//方案三 層序遍歷非遞歸import

import java.util.*;List

public class Solution {遍歷

public int TreeDepth(TreeNode root) {

  int count=0;
  int curCount=1;
  int nextCount=0;
  int totalCount=0;
  
  if(root==null)
      return totalCount;
    
  Queue<TreeNode> queue = new LinkedList<TreeNode>();
    
  queue.add(root);
    
  while(!queue.isEmpty()){
      
      TreeNode temp=queue.remove();
      count++;
      
      if(temp.left!=null){
         nextCount++;
          queue.add(temp.left);
      }
      if(temp.right!=null){
          nextCount++;
          queue.add(temp.right);
      }
      
       if(count==curCount){
          totalCount++;
          count=0;
          curCount=nextCount;
           nextCount=0;
      }
      
      
  }

    return totalCount;
}

}queue

//方案四:相似先序遍歷,實際上線找右子樹的最大高度,再找左子樹的最大高度

//也能夠先左子樹進棧,而後右子樹進棧,也就是先找左子樹的最大高度,再找右子樹的最大高度

import java.util.*;

public class Solution {

public int TreeDepth(TreeNode root) {

  int max=0;
  if(root==null)
      return max;
    
   Stack<TreeNode> stack1=new Stack<TreeNode>();
    stack1.push(root);
   Stack<Integer> stack2=new Stack<Integer>();
    stack2.push(0);
    
    while(!stack1.isEmpty()){
        
        TreeNode temp = stack1.pop();
        
        int num=stack2.pop();
        num++;
        
        if(num>max)
            max=num;
        
        if(temp.left!=null){
            stack1.push(temp.left);
            stack2.push(num);
        }
        
        if(temp.right!=null){
            stack1.push(temp.right);
            stack2.push(num);
        }
        
    }

    return max;
}

}

相關文章
相關標籤/搜索