递归相当与隐式的栈
public class Main{
public int getSucc(TreeNode<Integer>root,int p){
if(root==null)return -1;
Stack<TreeNode>stack=new Stack();
TreeNode<Integer>curr=root;
boolean isFound=false;//标记
while(curr!=null||!stack.isEmpty){
//左右支依次入栈
while(curr!=null){
stack.push(curr);
curr=curr.left;
}
if(!stack.isEmpty){
TreeNode<Integer>pop=stack.pop();//栈弹出的顺序就是中序遍历的顺序
//上一轮修改了标志位,当前出栈的值就是我们要的值
if(isFound){
return pop.value;
}else if(pop.value==p){
isFound=true;
}
curr=pop.right;//指向右子树继续外层循环
}
}
return -1;
}
}