Next Larger Value in BST

This question need some clarification of the TreeNode structure. 

Suppose the given TreeNode struct is as following:

Struct TreeNode {

int val;

TreeNode* left;

TreeNode* right;

TreeNode(int v) : val(v), left(NULL), right(NULL) {}

};

In this case, there is no parent node. 

1: The most straight forward solution is to do a in-order traversal until find the target value. Then, push out the getNext(). In this case, we are using the in-order in increasing feature of BST. The total time complexity is O(N), N is the total number of nodes of the given tree.

2: A future think about this structure: If we found the target, we need to go to the leftMost(root->right). If the root value is less than the target, we just go right. However, if the root value is larger than the target, we need to remember this node as prevNode and then go left.

int findTheNextLarger(TreeNode* root, int target) {
  if(!root) return -1;
  TreeNode* prev = root;
  while(root) {
    if(root->val == target) {
      TreeNode* tmp = goLeftMost(root->right);
      if(tmp == NULL) break;
      else return tmp->val;
    } else if(root->val < target) {
      root = root->right;
    } else {
      prev = root;
      root = root->left;
    }
  }
  return prev->val;
}

The most normal question we might have in this series problem is to "Given a node, find the next larger one."

struct TreeNode {

int val;

TreeNode* left;

TreeNode* right;

TreeNode* parent;

};

// if there is any parent node.
TreeNode* nextLargerOne(TreeNode *r) {
  if(r->right) {
    return goLeftMost(r->right);
  } else {
    TreeNode* q = r;
    TreeNode* x = q.parent;
    while(x != NULL && x->left != q) {
      q = x;
      x = x->parent;
    }
    return x;
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值