• [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;
        }
    };
  • 相关阅读:
    检测iphone设备是否越狱
    iphone震动提示
    单线,双线
    塔式服务器
    IPHONE锁屏控制代码
    iPhone开发之显示WiFi提示
    代码关闭程序的几种方法
    获取手机左边音量+ -按键的事件方法或私有api
    1u
    servlet在什么时候调用destroy()方法
  • 原文地址:https://www.cnblogs.com/vincently/p/4240253.html
Copyright © 2020-2023  润新知