只需要考虑这个结点是否有右子树
- 结点有右子树,那么下一个结点就是其右子树的最左结点
- 结点没有右子树,但是结点是其父结点的左结点,那么其下一个结点就是其父结点
- 结点没有右子树,又是父结点的右结点,那么就向上遍历,找到一个是父结点左儿子的结点,如果存在,则这个
父结点为所求结点
后两种情况可以放在一起看。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode father;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode inorderSuccessor(TreeNode p) {
TreeNode nextNode = null;
if (p.right != null) {
TreeNode rightNode = p.right;
while (rightNode.left != null) {
rightNode = rightNode.left;
}
nextNode = rightNode;
}
else if (p.father != null) {
TreeNode currentNode = p;
TreeNode fatherNode = p.father;
while (fatherNode != null && currentNode == fatherNode.right) {
currentNode = fatherNode;
fatherNode = currentNode.father;
}
nextNode = fatherNode;
}
return nextNode;
}
}