题目链接
很简单的一道题,二叉树中根据当前节点求出由中序遍历的下一个节点,分情况讨论
- 假如有右子树,那么右子树的最左节点就是要求的
- 假如没有右子树,那么就找祖先节点,直到找到一个祖先节点,使得该节点在该祖先节点的左子树中。
- 找到这样的祖先节点,直接返回,找不到,则返回Null
算法复杂度
- 时间复杂度: O ( n ) O(n) O(n),最坏的情况下,要遍历所有的节点。
- 空间复杂度: O ( 1 ) O(1) O(1),没有使用额外的空间
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode father;
* TreeNode(int x) { val = x; }
* }
*/
// 若右子树不为空,中序遍历右子树即可
// 若右子树为空,则需要找到它的一个祖先节点
// 使得其在祖先节点的左子树中,该祖先节点即为所求
/*
调试方法案例
有右子树
没有右子树有祖先节点
最后一个节点
*/
class Solution {
// 输入一个节点,获得它右子树中序遍历的第一个节点
private TreeNode InorderLast(TreeNode p){
if(p == null || p.right == null)
return null;
p = p.right;
while(p.left != null){
p = p.left;
}
return p;
}
public TreeNode inorderSuccessor(TreeNode p) {
if(p == null)
return null;
if(p.right != null)
return InorderLast(p);
while(p.father != null && p.father.right == p){
p = p.father;
}
if(p.father == null)
return null;
p = p.father;
return p;
}
}
C++实现
class Solution {
public:
TreeLinkNode* GetNext(TreeLinkNode* pNode)
{
if(pNode == NULL)
return NULL;
TreeLinkNode* ptr = NULL;
if(pNode->right != NULL){
TreeLinkNode* pRight = pNode->right;
while(pRight->left != NULL)
pRight = pRight->left;
ptr = pRight;
}else if(pNode->next != NULL){
TreeLinkNode* father = pNode->next;
TreeLinkNode* now = pNode;
while(father != NULL && now == father->right){
now = father;
father = father->next;
}
ptr = father;
}
return ptr;
}
};