package BinaryTree;
import java.util.Stack;
import static BinaryTree.Node.createBinaryTree;
import static BinaryTree.Node.inOrderNotRecursive;
public class LongestRoad {
/**
* 求二叉树的最长路径
* 我首先想到的就是使用非递归的后序遍历。因为非递归的后续遍历的栈中存放的就是一个路径节点
*/
public static int longestRoad(Node root){
if(root == null){
return 0;
}
Stack<Node> stack = new Stack<>();
//后序遍历最好写了,大循环条件栈不为空,因为根节点一直会存在,根节点访问了,出栈了,也就结束了
Node node = root;
stack.push(node);
node = node.left;
int max = 0;
while(!stack.isEmpty()){
while(node != null){
stack.push(node);
if(stack.size() > max){
max = stack.size();
}
node = node.left;
}
//有可能出栈,有可能不出栈,也有可能会持续出栈
//这里的持续出栈是栈顶元素和后一个元素