CC150 4.6 Successor

Successor: write an algorithm to find the "next" node(i.e. in-order successor) of a given node in a binary search tree. you may assume that each node has a link to its parent
已知BST中的一个node, 写算法找到下一个节点(比如:中序遍历)。假定每个节点都有父节点;
successor:  继承者;

思路:
1 由于是中序遍历,所以next node应该在given node(n)的右边;
2 右子树的哪个元素呢?应该是右子树最早访问的那个,即:右子树最左边的一个;
3 如果n没有右子树,怎么办?应该找到n的parent,叫做q;
     3.1  如果n在q左边->直接返回q;
     3.2  如果n在q右边(说明q已经被完整遍历)->应该找q的parent(x),x应该没有完整遍历;

如何得知x是否被完整遍历过?
     当我们从左节点到父节点时,左节点被完整遍历了,但是父节点没有;

伪代码:
Node inorderSucc(Node n){
      if(n has a right subtree)
      {
            return leftmost child of right subtree        
      }
     else//没有右子树,找n的父节点q
     {
          if(n in left of q)
          {
               return q    
          }
          else if(n in right of q)
          {
               n=n.parent; 
          }
     }
}   

C# 代码:
TreeNode inorderSuccess(TreeNode n)
        {
            if (n == null) return null;
            //如果有右子树->返回右子树的最左元素;
            if (n.right != null)
                return leftMostChild(n.right);
            else
            {
                TreeNode q = n;
                TreeNode x = q.parent;
                //向上,直到x的左边不是q
                while (x != null && x.left != q)
                {
                    q = x;
                    x = x.parent;
                }
                //n在q左边->返回q
                return x;
            }
        }
        TreeNode leftMostChild(TreeNode n)
        {
            if (n == null)
                return null;
            while (n.left != null)
                n = n.left;
            return n;
        }

小结:
面对复杂的问题,最好先写伪代码/画图,再写代码。有助于理清思路

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值