剑指 Offer 08.二叉树的下一个节点

题目链接
很简单的一道题,二叉树中根据当前节点求出由中序遍历的下一个节点,分情况讨论

  • 假如有右子树,那么右子树的最左节点就是要求的
  • 假如没有右子树,那么就找祖先节点,直到找到一个祖先节点,使得该节点在该祖先节点的左子树中。
  • 找到这样的祖先节点,直接返回,找不到,则返回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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值