Next Larger Value in BST

来源:互联网 发布:matlab调用python脚本 编辑:程序博客网 时间:2024/06/16 16:02

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;  }}

0 0
原创粉丝点击