• 99. Recover Binary Search Tree -- 找到二叉排序树中交换过位置的两个节点


    Two elements of a binary search tree (BST) are swapped by mistake.

    Recover the tree without changing its structure.

    Note:
    A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?

    /**
     * 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:
        void recoverTree(TreeNode* root) {
            stack<TreeNode*> s;
            TreeNode *p = root, *last = NULL, *p1 = NULL, *p2 = NULL;
            while(p || !s.empty())
            {
                while(p)
                {
                    s.push(p);
                    p = p->left;
                }
                if(!s.empty())
                {
                    p = s.top();
                    s.pop();
                    if(last && last->val >= p->val)
                    {
                        p2 = p;
                        if(!p1)
                            p1 = last;
                        else
                            break;
                    }
                    last = p;
                    p = p->right;
                }
            }
            swap(p1->val, p2->val);
        }
    };
  • 相关阅读:
    简单的多重背包
    完美子图
    活动投票
    人品问题
    售票系统
    最短路径
    优美值
    前端-常用函数记录-持续更新
    前端-单点登录中cookie中domain的思考
    大白话说GIT常用操作,常用指令git操作大全
  • 原文地址:https://www.cnblogs.com/argenbarbie/p/5411678.html
Copyright © 2020-2023  润新知