285. Inorder Successor in BST

题目:

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.

链接: http://leetcode.com/problems/inorder-successor-in-bst/

5/11/2017

自己没做好,思路是对的,但是没有想好如果碰到匹配该怎么办,尝试着退出。其实碰到匹配的话应该继续走右子树,然后找右子树里面的最左边的点。

 1 public class Solution {
 2     public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
 3         if (root == null || p == null) return null;
 4 
 5         TreeNode tmp = null;
 6         TreeNode node = root;
 7         
 8         while (node != null) {
 9             if (p.val < node.val) {
10                 tmp = node;
11                 node = node.left;
12             } else {
13                 node = node.right;
14             }
15         }
16         return tmp;
17     }
18 }

更多讨论:

https://discuss.leetcode.com/topic/25076/share-my-java-recursive-solution

posted @ 2017-05-12 08:02  panini  阅读(137)  评论(0编辑  收藏  举报