【LeetCode-树】后继者

题目描述

设计一个算法,找出二叉搜索树中指定节点的“下一个”节点(也即中序后继)。
如果指定节点没有对应的“下一个”节点,则返回null。
示例:

输入: root = [2,1,3], p = 1

  2
 / \
1   3

输出: 2

输入: root = [5,3,6,2,4,null,null,1], p = 6

      5
     / \
    3   6
   / \
  2   4
 /   
1

输出: null

题目链接: https://leetcode-cn.com/problems/successor-lcci/

思路1

本质上是二叉树的中序遍历。使用 pre 表示当前节点的前一个节点,如果 pre->val==目标值,输出当前节点即可。代码如下:

/**
 * 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==nullptr || p==nullptr) return nullptr;

        stack<pair<TreeNode*, bool>> s;
        s.push(make_pair(root, false));
        TreeNode* pre = nullptr;
        while(!s.empty()){
            TreeNode* curNode = s.top().first;
            bool visit = s.top().second;
            s.pop();
            if(!visit){
                if(curNode->right!=nullptr) s.push(make_pair(curNode->right, false));
                s.push(make_pair(curNode, true));
                if(curNode->left!=nullptr) s.push(make_pair(curNode->left, false));
            }else{
                if(pre!=nullptr && pre->val==p->val) return curNode;
                if(curNode->val==p->val) pre = curNode;

            }
        }
        return nullptr;
    }
};
  • 时间复杂度:O(n)
  • 空间复杂度:O(h)
    h 为树高。

思路2

使用 dfs 来做。使用变量 pre 记录遍历过程中当前节点 cur 的前一个节点,如果 pre->val==p->val,则将 ans 设为 cur 并返回。需要注意的是,在返回之前要把 pre 重置为 null。代码如下:

/**
 * 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 {
private:
    TreeNode* pre;
    TreeNode* ans;
public:
    TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
        pre = NULL;
        ans = NULL;
        inOrder(root, p);
        return ans;
    }

    void inOrder(TreeNode* cur, TreeNode* p){
        if(cur==NULL) return;

        inOrder(cur->left, p);
        if(pre!=NULL){
            if(pre->val==p->val){
                ans = cur;
                pre = NULL;  // 要置为null,例子[5,3,6,2,4,null,null,1], 1
                return;
            }
        }
        pre = cur;
        inOrder(cur->right, p);
    }
};
posted @ 2020-05-06 17:34  Flix  阅读(192)  评论(0编辑  收藏  举报