首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 99 Recover Binary Search Tree

Leetcode 99 Recover Binary Search Tree

作者头像
triplebee
发布2018-01-12 14:55:07
6020
发布2018-01-12 14:55:07
举报

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?

修正二叉排序树中的一个错误对,不改变树结构。

中序遍历一下,找到逆序的两个地方,交换值就行了,题目要求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 dfs(TreeNode* root,vector<TreeNode*> &path)
    {
        if(!root) return ;
        dfs(root->left,path);
        path.push_back(root);
        dfs(root->right,path);
    }
    void recoverTree(TreeNode* root) {
        vector<TreeNode*> path;
        dfs(root,path);
        int st=0,en=path.size()-1;
        while(st<en)
        {
            if(path[st]->val<path[st+1]->val) 
                st++;
            else if(path[en]->val>path[en-1]->val) 
                en--;
            else
            {
                swap(path[en]->val,path[st]->val);
                return ;
            }
        }
        
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-10-08 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档