代码实现:
import java.util.ArrayList;
import java.util.Stack;
public class Solution {
ArrayList<TreeLinkNode> list = new ArrayList<>();
public TreeLinkNode GetNext(TreeLinkNode pNode) {
//pNode给的使第二段的节点,所以我们需要找到根节点
TreeLinkNode root = pNode;
//循环找到根节点
while(root.next != null) root = root.next;
//创建一个栈辅助中序遍历
Stack<TreeLinkNode> s = new Stack<>();
//临时变量
TreeLinkNode p = null;
while(!s.isEmpty() || root != null){
while(root != null){
s.push(root);
root = root.left;
}
//弹出栈的最后进入的节点
p = s.pop();
//放入list
list.add(p);
//跳出上边循环则说明左边的已经压入完毕,压入右边的
root = p.right;
}
//在list中找到相等的那个节点
int count = list.size();
for(int i = 0; i<count-1; i++){
TreeLinkNode cur = list.get(i);
//返回相等节点的下一个节点
if(cur == pNode) return list.get(i+1);
}
return null;
}
}