题目:找出中序遍历二叉树的后继
思路:
分情况讨论:
1.当节点有右子树时,其后继为右子树的最左节点,如C的后继为B。
2.当节点没有右子树时,比如B和D,B的后继为父节点D,D的后继为一直向上的F节点,G没有后继节点。可以发现规律,
若当前节点有父亲节点,其父亲节点为其他节点的左子树,则当前节点有后继。若当前节点是父节点的左子树,则后继为其父节点;若当前节点是父节点的右子树,则一直往上找。
/**
* 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) {
//分类讨论
//当节点存在右子树,其中序后继为右子树的最左节点
if(p.right != null){
p = p.right;
while(p.left != null){
p = p.left;
}
return p;
}
//当节点不存在右子树,且该节点其父节点是其他节点的左子树,则其他节点是该节点的后继
while(p.father != null && p == p.father.right)p = p.father;
return p.father;
}
}