zoukankan      html  css  js  c++  java
  • [LeetCode] 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?

    思路:中序递归的思路。用pre记录前一个节点,找出违反二叉搜索树规则的节点。中序遍历序列中,第一次违反二叉搜索树规则的节点的前一个节点是要修改的节点。第二次违反二叉搜索树规则的节点本身是要修改的节点.如果是中序遍历相邻的节点出错直接两次都违反。

    /**
     * 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) {
            if (root == NULL) return;
            
            stack<TreeNode*> s;
            TreeNode* p = root;
            TreeNode* pre = NULL;
            TreeNode* wrong_node1 = NULL;
            TreeNode* wrong_node2 = NULL;
            int flag = 1;
            
            while (p != NULL || !s.empty()) {
                if (p != NULL) {
                    s.push(p);
                    p = p->left;
                } else {
                    p = s.top();
                    s.pop();
                    if (pre == NULL) {
                        pre = p;
                    } else {
                        if (pre->val > p->val) {
                            if (flag == 1) {
                                wrong_node1 = pre;
                                wrong_node2 = p;
                                flag = 2;
                            } else {
                                wrong_node2 = p;
                            }
                        }
                        pre = p;
                    }
                    p = p->right;
                }
            }
            
            int temp = wrong_node1->val;
            wrong_node1->val = wrong_node2->val;
            wrong_node2->val = temp;
        }
    };
  • 相关阅读:
    IE设置代理后登录QQ再关闭代理仍然可以使用QQ
    ubuntu14.04下Qt开发环境搭建遇到的问题
    CButtonST使用技巧: CButtonST简介
    springboot webapi 支持跨域 CORS
    服务注册和发现 Eureka
    开发框架 springBoot
    springBoot springCloud
    springBoot 微服务
    springBoot AOP环绕增强、自定义注解、log4j2、MDC
    springBoot 热部署
  • 原文地址:https://www.cnblogs.com/vincently/p/4240253.html
Copyright © 2011-2022 走看看