[leetcode]Inorder Successor in BST
2015-12-31 14:29
477 查看
Problem
Given a binary search tree and a node in it, find the in-order successor of that node in the BST.Note: If the given node has no in-order successor in the tree, return
null.
Solution 1. Iterative 利用BST的排序特性
找target节点的successor, 就是找比它大的最小的那个节点。利用BST的特性:用runner从根开始遍历节点
1) 如果runner的值比target节点小或者相等,排除左边往右边找,因为该节点左边的都比该节点小。
2) 如果一个节点比target节点大,那它就有可能是要找的successor, 暂且标记为successor.
重复上面两步,直到runner为空
Time O(N), Space O(1)
class Solution { public: TreeNode* inorderSuccessor(TreeNode* root, TreeNode* target) { if(!root || !target) return NULL; TreeNode* runner = root, *suc = NULL; while(runner){ if(runner->val > target->val){ suc = runner; runner = runner->left; } else { runner = runner->right; } } return suc; } };
Solution 2. Recursive 同样利用BST的排序特性
class Solution { public: TreeNode* inorderSuccessor(TreeNode* root, TreeNode* target) { if(!root) return NULL; if(root->val <= target->val){ return inorderSuccessor(root->right, target); } else{ TreeNode* rst = inorderSuccessor(root->left, target); return rst ? rst : root; } } };
Solution 3. 利用 inorder traversal 的特性
我的思路是 : 从根节点开始向下遍历,如果找到目标节点,那么向上返回一层的那个root节点就是答案。However,写出来的code不work。
有哪位大神看到了帮忙指导一下啊。。
class Solution { TreeNode* helper(TreeNode* root, TreeNode* target, bool& found){ if(!root) return NULL; if(target == root) { found = true; return NULL;} TreeNode* left = helper( root->left, target, found); if(found) return root; return helper(root->right, target, found); } public: TreeNode* inorderSuccessor(TreeNode* root, TreeNode* target) { bool found = false; return helper(root, target, found); } };
相关文章推荐
- MIT Introduction to Algorithms 学习笔记(六)
- How To Migrate NTFS Volumes From A LeftHand SAN To Some Other Storage Array
- Binary Search Tree Iterator,Reverse Nodes in k-Group
- [LeetCode] Convert Sorted List to Binary Search Tree
- [LeetCode] Convert Sorted Array to Binary Search Tree
- [LeetCode] Recover Binary Search Tree
- [LeetCode] Validate Binary Search Tree
- [LeetCode] Unique Binary Search Tree
- Convert Sorted Array to Binary Search Tree
- LeetCode:Binary Search Tree相关题目合集
- LeetCode-Convert Sorted Array to Binary Search Tree
- Convert Sorted Array(List) to Binary Search Tree
- Validate Binary Search Tree
- convert sorted array to binary search tree
- Binary Tree Inorder Traversal
- Binary Search Tree Iterator
- Binary Tree Postorder Traversal
- Kth Smallest Element in a BST
- [Leetcode]Recover Binary Search Tree
- [Leetcode]Validate Binary Search Tree