题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
解题思路
运用层次遍历非递归的方法,当进栈一个元素,就进num++。出栈一个元素就和max进行比较,如果max<num,就更新max=num。
题目链接.
代码块
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
import java.util.Stack;
public class Solution {
public int TreeDepth(TreeNode root) {
Stack<TreeNode> stack=new Stack<TreeNode>();
Stack<Integer> stack1=new Stack<Integer>();
int num=0;
int max=0;
if(root==null){
return max;
}
if(root!=null){
stack.push(root);
stack1.push(0);
}
while(!stack.isEmpty()){
TreeNode temp=stack.pop();
num=stack1.pop();
num++;
if(max<num){
max=num;
}
if(temp.left!=null){
stack.push(temp.left);
//System.out.println("left:"+num);
stack1.push(num);
}
if(temp.right!=null){
stack.push(temp.right);
//System.out.println("right:"+num);
stack1.push(num);
}
}
return max;
}
}