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; }}
- Next Larger Value in BST
- next value of BST
- Find next node in bst
- CareerCup Find the ceiling value present in the BST of a given ke
- LCA in BST
- Inorder Successor in BST
- Inorder Successor in BST
- Inorder Successor in BST
- Inorder Successor in BST
- Delete node in BST
- Inorder Successor in BST
- [刷题]Inorder Successor in BST
- **LeetCode-Inorder Successor in BST
- [LeetCode285]Inorder Successor in BST
- [leetcode]Inorder Successor in BST
- leetcode Inorder Successor in BST
- Delete Node in a BST
- Counting Nodes in a BST
- read obj in matlab
- android_java.lang.IllegalStateException: Fragment bb{42261900} not attached to Activity
- HDU 2333Assemble(简单二分)
- LeetCode--No.171--Excel Sheet Column Number
- LeetCode--No.357--Count Numbers with Unique Digits
- Next Larger Value in BST
- 软件概要设计与详细设计的区别
- 设计模式-状态模式
- 函数指针的特殊性, 定义和调用都有两种做法
- Leetcode Sort List
- LeetCode--No.343--Integer Break
- Android动画之---补间动画
- IOS弹出提示框
- Power of Three