Problem Link:

https://oj.leetcode.com/problems/recover-binary-search-tree/

We know that the inorder traversal of a binary search tree should be a sorted array. Therefore, we can compare each node with its previous node in the inorder to find the two swapped elements.

There are at most two cases that current_node < prev_node:

  1. If the two swapped elements are adjacent, then there is only one occurrence that current_node < prev_node. The two elements are just the current_node and prev_node.
  2. If the two swapped elements are not neighbors, then there are two occurrences that current_node < prev_node. The two elements are the prev_node in the first occurrence and the current_node in the second occurrence.

The code is as follows.

# Definition for a  binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution:
# @param root, a tree node
# @return a tree node
def recoverTree(self, root):
"""
Traverse the tree in the order of inorder and compare the node to its previous node.
There are at most two occurrences that prev_node < current_node, if there are two elements swapped.
If there is only one occurrence, then the two swapped nodes are prev_node and current_node.
If there are two occurrences, then the two swapped nodes are prev_node in the first occurrence and current_node in the second occurrence.
"""
prev_node = None
current_node = None
stack = []
p = root
res1 = None
res2 = None
while stack or p:
if p:
stack.append(p)
p = p.left
else:
current_node = stack.pop()
# Compare current node and previous node
if prev_node:
if prev_node.val > current_node.val:
if res1:
res2 = current_node
break
else:
res1 = prev_node
res2 = current_node
prev_node = current_node
p = current_node.right
res1.val, res2.val = res2.val, res1.val
return root

【LeetCode OJ】Recover Binary Search Tree的更多相关文章

  1. 【LeetCode练习题】Recover Binary Search Tree

    Recover Binary Search Tree Two elements of a binary search tree (BST) are swapped by mistake. Recove ...

  2. 【LeetCode 99】Recover Binary Search Tree

    Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing ...

  3. 【LeetCode OJ】Validate Binary Search Tree

    Problem Link: https://oj.leetcode.com/problems/validate-binary-search-tree/ We inorder-traverse the ...

  4. LeetCode OJ 99. Recover Binary Search Tree

    Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing ...

  5. LeetCode OJ:Recover Binary Search Tree(恢复二叉搜索树)

    Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing ...

  6. 【LeetCode练习题】Validate Binary Search Tree

    Validate Binary Search Tree Given a binary tree, determine if it is a valid binary search tree (BST) ...

  7. 【leetcode】Recover Binary Search Tree

    Recover Binary Search Tree Two elements of a binary search tree (BST) are swapped by mistake. Recove ...

  8. Leetcode 笔记 99 - Recover Binary Search Tree

    题目链接:Recover Binary Search Tree | LeetCode OJ Two elements of a binary search tree (BST) are swapped ...

  9. 【leetcode刷题笔记】Recover Binary Search Tree

    Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing ...

随机推荐

  1. PHP 中:: -> self $this 操作符的区别

    访问PHP类中的成员变量或方法时, 如果被引用的变量或者方法被声明成const(定义常量)或者static(声明静态),那么就必须使用操作符::, 反之如果被引用的变量或者方法没有被声明成 const ...

  2. uva 10271 (dp)

    题意:有n个数据,给定k,要从中选出k+8个三元组(x,y,z,其中x<=y<=z),每选一次的代价为(x-y)^2,求最小代价和. [解题方法] 将筷子按长度从大到小排序 排序原因: 由 ...

  3. [原创]C#应用WindowsApi实现查找\枚举(FindWindow、EnumChildWindows)窗体控件,并发送消息。

    首先介绍基本WindowsApi: public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); 函 ...

  4. Solr环境搭建过程中遇到的问题

    Solr下载地址:http://www.apache.org/dyn/closer.lua/lucene/solr/6.3.0 Solr搭建步骤转自:http://blog.csdn.net/wbcg ...

  5. [划分树] POJ 2104 K-th Number

    K-th Number Time Limit: 20000MS   Memory Limit: 65536K Total Submissions: 51732   Accepted: 17722 Ca ...

  6. 自定义带动画的Toast

    一.style样式: 1.  // 移动和透明渐变结合的动画 <style name="anim_view">        <item name="@ ...

  7. 【Python扩展阅读【转】】字符串的方法及注释

      capitalize()   把字符串的第一个字符改为大写   casefold()   把整个字符串的所有字符改为小写   center(width)   将字符串居中,并使用空格填充至长度wi ...

  8. sql 2008 修改链接服务器 Rpc &Rpc Out

    From: http://blog.csdn.net/gnolhh168/article/details/41725873 USE [master] GO EXEC master.dbo.sp_ser ...

  9. JQuery设置时间段下拉选择 时间下拉选择

    $(document).ready(function() { var arrT = []; var tt = "{0}:{1}"; for (var i = 0; i < 2 ...

  10. linux内核学习之三 跟踪分析内核的启动过程

    一   前期准备工作       1 搭建环境 1.1下载内核源代码并编译内核 创建目录,并进入该目录: 下载源码: 解压缩,并进入该目录:xz -d linux-3.18.6.tar.xz tar ...