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.

 

本题要求按中序遍历节点p的下一个节点是什么。这道题还是很有难度的,虽然递归实现起来比较容易。思路是,先思考,一个节点按中序的话,它的后继节点是什么呢?有两种情况,一种是该节点有右子树的话,后继节点一定在这个右子树的最左面的节点上,如果该节点没有右子树的话,那么后继节点就在该节点的父节点上面。实现起来可以按照这个思路进行,即如果该节点小于等于target的节点值,则从它的右子树上面找;而如果该节点大于target值,那么查看该节点是否有右子树(因为递归的顺序是从树的最上面往下的,所以只有可能是该节点的父节点,而不可能是target节点的右子树节点),如果没有,则返回父节点,否则,返回右子树最左面的节点。代码如下:

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
12         if(root==null) return null;
13         if(root.val<=p.val){
14             return inorderSuccessor(root.right,p);
15         }else{
16             TreeNode left = inorderSuccessor(root.left,p);
17             return left!=null?left:root;
18         }
19     }
20 }

 

posted @ 2017-03-24 11:35  CodesKiller  阅读(158)  评论(0编辑  收藏  举报