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?

    中序遍历,对于BST,其中序序列是有序的,所以只要找出中序序列中的逆序对,但是要注意保存中间节点,可以使用全局变量,也可以使用引用。

     1 /**
     2  * Definition for binary tree
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     void inorder(TreeNode *root, TreeNode *&pos1, TreeNode *&pos2, TreeNode *&pre) {
    13         if (root == NULL) return;
    14         inorder(root->left, pos1, pos2, pre);
    15         if (pre != NULL && pre->val > root->val) {
    16             if (pos1 == NULL) {
    17                 pos1 = pre;
    18                 pos2 = root;
    19             } else {
    20                 pos2 = root;
    21             }
    22         }
    23         pre = root;
    24         inorder(root->right, pos1, pos2, pre);
    25     }
    26     
    27     void recoverTree(TreeNode *root) {
    28         TreeNode *pos1, *pos2, *pre;
    29         pos1 = pos2 = pre = NULL;
    30         inorder(root, pos1, pos2, pre);
    31         swap(pos1->val, pos2->val);
    32     }
    33 };
  • 相关阅读:
    POJ
    Parallel Computing–Cannon算法 (MPI 实现)
    POJ
    POJ 2240
    IOS
    iOS
    js遍历map匹配数据和js遍历数组匹配map数据
    vue v-on:click传递动态参数
    vue 权限控制按钮3种样式、内容、以及跳转事件
    vue v-show与v-for同时配合v-bind使用并在href中传递多个参数的使用方法
  • 原文地址:https://www.cnblogs.com/easonliu/p/3644294.html
Copyright © 2011-2022 走看看