题目描述
输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
好吧,看到这题我第一时间想到的又是用压栈的方法,笑哭。
思路:
从根节点开始压栈,顺着一条路径开始往下走,直到到叶子节点,在压栈的过程中记录下遍历的节点数。到叶子节点后,把叶子节点赋值为null,并弹出改叶子节点,防止下次再次走这条路径。当栈为空时,则表示已遍历完所有路径,返回深度。
代码:
import java.util.*;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public int TreeDepth(TreeNode root) {
TreeNode head = root;
//当根节点都为空时,返回0
if(root == null){
return 0;
}
int number = 1;
int endNumber = 0;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
//遍历二叉树的所有路径
while(root != null){
//左子树不为空时,往左子树方向遍历
if(head.left != null){
stack.push(head.left);
head = head.left;
number++;
}
//右子树不为空时,往右子树方向遍历
if(head.right != null){
stack.push(head.right);
head = head.right;
number++;
}
//左右子树都为空,即该节点是叶子节点时,记录下遍历节点数,如果遍历节点数比前面遍历的节点数大,则保留这个大的遍历节点数
//把该叶子节点赋值为空,并从栈中弹出该叶子节点
if(head.left == null && head.right == null){
if(number > endNumber){
endNumber = number;
number--;
}else{
number--;
}
stack.pop();
if(stack.isEmpty()){
return endNumber;
}
if(head == stack.peek().left){
head = stack.peek();
head.left = null;
}
if(head == stack.peek().right){
head = stack.peek();
head.right = null;
}
}
}
return endNumber;
}
}