首页 > 其他 > 详细

CC150 4.5

时间:2014-11-27 08:01:44      阅读:248      评论:0      收藏:0      [点我收藏+]

4.5 Write an algorithm to find the ‘next’ node (i.e., in-order successor) of a given node in a binary search tree where each node has a link to its parent.

// BST.

class Node
{
  Node parent;
  Node left;
  Node right;
}

Node min(Node node)
{
  if (node == null)
    return null;
  while(node.left != null)
    node = node.left;
  return node;
}

// in-order ?
Node next(Node node)
{
  if (node == null)
    return null;
    
  if (node.right != null)
  {
    Node toReturn = node.right;
    while (toReturn.left != null)
    {
      toReturn = toReturn.left;
    }
    return toReturn;
  }
  
  while( node != null)
  {
    if (node == node.parent.left)
      return node.parent;
    else
      node = node.parent;
  }
  
  return null;
}


CC150 4.5

原文:http://7371901.blog.51cto.com/7361901/1583044

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!