给定树的根结点指针TreeNode* root和结点的值int p,编写一个函数,寻找该二叉树中指定结点的下一个结点(即中序遍历的后继),并返回p结点的后继结点的值。保证结点的值是小于等于100000的正数且没有重复值,若不存在后继返回-1。
public int findSucc(TreeNode root, int p) {
// 非递归中序遍历,栈
Stack list = new Stack();
if(root == null || root.left == null){
return -1;
}
TreeNode cur = root;
boolean flag = false;
int res = -1;
while(cur != null || !list.isEmpty()){
if(cur != null){
list.push(cur);
cur = cur.left;
}else{
cur = list.pop();
System.out.println(cur.val);
if(flag){
res = cur.val;
break;
}
if(cur.val == p){
flag = true;
}
cur = cur.right;
}
}
return res;
}



