题意:给出一个带父结点的二叉树中的一个结点,求出中序遍历中该结点的下一个结点
思路:可以先找出根结点,之后进行中序遍历,如果当前结点的前一个结点为所给结点,那这个结点就是答案
/*
public class TreeLinkNode {
int val;
TreeLinkNode left = null;
TreeLinkNode right = null;
TreeLinkNode next = null;
TreeLinkNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public TreeLinkNode node, ans, pre;
public TreeLinkNode GetNext(TreeLinkNode pNode)
{
node = pNode;
TreeLinkNode root = pNode;
while (root.next != null)
root = root.next;
inorder(root);
return ans;
}
public void inorder(TreeLinkNode root) {
if (ans != null)
return;
if (root.left != null)
inorder(root.left);
if (pre == node)
ans = root;
pre = root;
if (root.right != null)
inorder(root.right);
}
}