import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Stack;
import org.junit.Test;
public class solution {
@Test
public void testFunc(){
TreeNode root = new TreeNode(1);
TreeNode root2 = new TreeNode(2);
TreeNode root3 = new TreeNode(3);
root.left=root2;
root.right = root3;
int searchNode = searchNode(root, 3);
System.out.println(searchNode);
}
// 找出中序遍历下某个元素的下一个节点---中序遍历的非递归调用
public int searchNode(TreeNode root, int target){
if (root==null) {
return -1;
}
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode cur = root;
boolean flag=false;
while(cur!=null || !stack.isEmpty()){
while (cur!=null) {
stack.push(cur);
cur = cur.left;
}
if (cur==null && !stack.isEmpty()) {
cur = stack.pop();
if (flag) {
if (cur==null) {
return -1;
}
return cur.val;
}
if (cur.val==target) {
flag=true;
}
cur = cur.right;
}
}
return -1;
}
}