[Leetcode] 285. Inorder Successor in BST 解题报告

来源:互联网 发布:剑灵捏脸数据图下载 编辑:程序博客网 时间:2024/05/21 06:18

题目

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.

思路

1、O(n)的解法:最开始容易想到的思路就是直接进行中序遍历。一旦发现我们遍历到的当前结点的前驱是p,就更新结果。这种思路的时间复杂度是O(n),空间复杂度是O(1)。
2、O(logn)的解法:我开始的想法是分两种情况:1)p的右子树不为空,那么p的后继结点就是p的右子树上的最左侧的结点;2)p的右子树为空,那么p的后继结点就是它的祖先中第一个比它值大的结点(也有可能为空),在这种情况下,需要开辟一个栈空间来存贮p的所有祖先结点。这种思路可以把时间复杂度可以降低到O(logn),但是空间复杂度却是O(logn)。后来看到下面这个更巧妙的算法:如果p的值比root的值大或者p就是root,那么p的后继不可能出现在root以及root的左子树上,所以我们只需要在root的右子树上继续找;如果p的值比root的值小,那么p的直接后继既有可能是root,也有可能是root的左子树上的某个结点,此时需要更新答案,并且在root的左子树上继续找。这种思路完美地统一处理了p的右子树是否为空两种情况,并且将空间复杂度降低到了O(1)。

代码

1、O(n)的解法:

/**  * Definition for a binary tree node.  * struct TreeNode {  *     int val;  *     TreeNode *left;  *     TreeNode *right;  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}  * };  */  class Solution {  public:      TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {          if (!root) {              return NULL;          }          inorderSuccessor(root->left, p);          if (pre == p) {              ret = root;          }          pre = root;          inorderSuccessor(root->right, p);          return ret;      }  private:      TreeNode *pre = NULL, *ret = NULL;  };
2、O(logn)的解法:

/**  * Definition for a binary tree node.  * struct TreeNode {  *     int val;  *     TreeNode *left;  *     TreeNode *right;  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}  * };  */  class Solution {  public:      TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {          if (root == NULL || p == NULL) {              return NULL;          }          TreeNode *ret = NULL;          while (root) {              if (p->val < root->val) {                  ret = root;                  root = root->left;              }              else {                  root = root->right;              }          }          return ret;      }  }; 

原创粉丝点击