Inorder Successor in Binary Search Tree
2016-08-07 00:05
344 查看
Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
Another solution
public class Solution { public TreeNode inorderSuccessor(TreeNode root, TreeNode n) { if (root == null) return null; if (n.right != null) { return min(n.right); } TreeNode succ = null; while (root != null) { if (n.val < root.val) { //左子树的successor都是当前树的root。 succ = root; root = root.left; } else if (n.val > root.val) root = root.right; else break; } return succ; } public TreeNode min(TreeNode n) { if (n.left != null) { return min(n.left); } return n; } } class TreeNode { TreeNode left; TreeNode right; int val; public TreeNode(int i) { val = i; } }
Another solution
public class Solution { TreeNode pre = null; TreeNode succ = null; void inorderSuccessorII(TreeNode root, TreeNode p) { if (root == null || succ != null) return; inorderSuccessor(root.left, p); if (pre == p) { succ = root; } pre = root; inorderSuccessor(root.right, p); } }
相关文章推荐
- Inorder Successor in Binary Search Tree
- Inorder Successor in Binary Search Tree
- Inorder Successor in Binary Search Tree BST中找中序遍历的后继节点
- Data Structure Binary Search Tree: Inorder Successor in Binary Search Tree
- [Google] Inorder Successor in Binary Search Tree, Solution
- LintCode : Inorder Successor in Binary Search Tree
- Tree_Graph Inorder Successor in Binary Search Tree BST中找中序遍历的后继节点 @CareerCup
- Inorder Successor in Binary Search Tree
- [Google] Inorder Successor in Binary Search Tree, Solution
- Inorder Successor in Binary Search Tree
- 中序遍历二叉排序树:BinarySearchTree:Create a tree and InorderTree
- Binary Tree Inorder Traversal, Binary Search Tree Iterator
- 255. Verify Preorder Sequence in Binary Search Tree
- Verify Preorder Sequence in Binary Search Tree
- Verify Preorder/Inorder/Postorder Sequence in Binary Search Tree
- 用linked list实现binary-search-tree及其inorderwalk(中序遍历)
- Data Structure Binary Search Tree: Find k-th smallest element in BST (Order Statistics in BST)
- [Leetcode]Verify Preorder Sequence in Binary Search Tree
- [leetcode 255] Verify Preorder Sequence in Binary Search Tree ---先序遍历验证二叉搜索树
- [Leetcode][JAVA] Recover Binary Search Tree (Morris Inorder Traversal)