Martyn Ye

A geek & a dreamer

  • 主页
  • 随笔
所有文章 友链 关于我

Martyn Ye

A geek & a dreamer

  • 主页
  • 随笔

[LeetCode] Recover Binary Search Tree

2016-03-09

Analysis:

Use in-order traversal to find the disorder node pairs.

  • If there is one pair: that means the swap nodes are adjacent.
  • If ther are two pair: they are not next to each other.

Finally swap them by value. This is not the optimal solution. BTW

Time Complexity:

  • O(n)

Space Complexity:

  • O(n)

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution(object):
def recoverTree(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
if root is None: return

vec = []
prev = None
node1, node2 = None,None
p = root

count = 0
while len(vec) > 0 or p is not None:
if p is not None:
vec.append(p)
p = p.left
else:
p = vec.pop()
if prev is None:
prev = p
else:
if prev.val > p.val:
count += 1
if node1 is None:
node1 = prev
node2 = p
elif count > 1:
node2 = p
prev = p
p = p.right

node1.val, node2.val = node2.val, node1.val
赏

谢谢你请我吃糖果

  • LeetCode
  • Tree

扫一扫,分享到微信

微信分享二维码
[LeetCode] House Robber III
[LeetCode] Implement Queue using Stacks
© 2024 Martyn Ye
Hexo Theme Yilia by Litten
  • 所有文章
  • 友链
  • 关于我

tag:

  • Misc
  • LeetCode
  • Dynamic Programming
  • Binary Tree
  • Greedy
  • Breadth First Search
  • Binary Search
  • Math
  • System Design
  • Binary Search Tree
  • Backtracking
  • Heap
  • Design
  • Depth First Search
  • Build Binary Tree
  • array
  • Tree
  • Stack
  • Reservoir Sampling
  • Bit Manipulation
  • Deep-First-Search
  • Trie
  • Hash Table
  • Two Pointers
  • String
  • Android
  • Github
  • Data Structure Design
  • C++
  • Sort
  • Linked List
  • Bit-Manipulation
  • LintCode
  • Merge Sort
  • Mafia fight
  • Array
  • Heap Sort
  • Open Source
  • Summary

    缺失模块。
    1、请确保node版本大于6.2
    2、在博客根目录(注意不是yilia根目录)执行以下命令:
    npm i hexo-generator-json-content --save

    3、在根目录_config.yml里添加配置:

      jsonContent:
        meta: false
        pages: false
        posts:
          title: true
          date: true
          path: true
          text: false
          raw: false
          content: false
          slug: false
          updated: false
          comments: false
          link: false
          permalink: false
          excerpt: false
          categories: false
          tags: true
    

Martyn's Playground