题目
给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
解题
分两种情况:
1.如果有右孩子,如果有,中继下一个节点是,右子树的最左边的节点
2.如果没有左孩子,找父节点,如果是父节点的左孩子,父节点就是下一个
代码
/**
* 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 pNode) {
if(pNode == null )
return null;
if(pNode.right != null) {
pNode = pNode.right;
while(pNode.left != null)
pNode = pNode.left;
return pNode;
}
while(pNode.father != null) {
if(pNode.father.left==pNode)
return pNode.father;
pNode=pNode.father;
}
return null;
}
}