Recovery Binary Search Tree Leetcode Python
来源:互联网 发布:日本二战殖民地知乎 编辑:程序博客网 时间:2024/04/28 16:11
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
题目要求找到BST中被swap的两个节点并把它们复原,这里考虑到是BST 我们可以用Inorder traverse,如果没有被调换之前的所有节点值满足序号从小到大 数组依次增大。 如果被调换,假如原来序列为1 2 3 4 5 6 7,这里假设1和7被调换,最后为7 2 3 4 5 6 1 第一个被调换的数是比后面的数大 7>2 第二个被调换的是1 比前面的小 6>1,依次取出 7 和1 将他们换回去,可以得到答案。
This problem can be solved by using inorder traverse, in general BST if we inorder traverse the tree, we can get an array with increasing order. However, if two of the nodes are swapped, lets assume the original order is 1 2 3 4 5 6 7, we swap 1 and 7 here. The result will become 7 2 3 4 5 6 1, the first swapped element is the node greater than its post node, which is 7>2. The second node will be the node smaller than its pre node 6>1.
Now we need to swap these two nodes, we get the answer.
# Definition for a binary tree node# class TreeNode:# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution: # @param root, a tree node # @return a tree node def inorder(self,root): if root: self.inorder(root.left) if self.prev and self.prev.val>root.val: self.n2=root if self.n1==None: self.n1=self.prev self.prev=root self.inorder(root.right) def recoverTree(self, root): self.n1,self.n2=None,None self.prev=None self.inorder(root) self.n1.val,self.n2.val=self.n2.val,self.n1.val return root
- Recovery Binary Search Tree Leetcode Python
- 【LeetCode with Python】 Validate Binary Search Tree
- Validate Binary Search Tree Leetcode Python
- [Leetcode] 98. Validate Binary Search Tree @python
- python:leetcode之Recover Binary Search Tree
- leetcode 99 Recover Binary Search Tree (python)
- leetcode 98 Validate Binary Search Tree (python)
- 【Leetcode】【python】Validate Binary Search Tree
- 【Leetcode】【python】Recover Binary Search Tree
- [Leetcode]Binary Search Tree
- Leetcode -- Python -- Convert Sorted Array to Binary Search Tree
- 【LeetCode with Python】 Convert Sorted Array to Binary Search Tree
- 108. Convert Sorted Array to Binary Search Tree Leetcode Python
- 109.Convert Sorted List to Binary Search Tree Leetcode Python
- [leetcode] @python Convert Sorted List to Binary Search Tree
- [leetcode: Python] 108. Convert Sorted Array to Binary Search Tree
- [leetcode: Python]501. Find Mode in Binary Search Tree
- 【Leetcode】【python】Convert Sorted Array to Binary Search Tree
- 对C++中指向类的非静态成员的指针的认识
- 做个爱读书的程序员
- 鬃仔罪昨捉紫钻鬃钻兹谞资谆抓椎醉状缀
- 线程通信
- 棕酌赘祝奏妆遵坠阻奏妆抓卒装爪尊赚奏
- Recovery Binary Search Tree Leetcode Python
- beyond compare 命令行调用方法
- C语言保留字
- 高压力, 多CPU, 高内存环境下JVM设置
- 字坐祖做灼注桌琢祝遵醉揍踪谆缀组浊昨
- Error: Registry key 'Software\JavaSoft\Java Runtime Environment'\CurrentVersion' 解决方案
- GreenDao简明教程(查询,Querying)
- Fragment 与Fragment之间的通信
- 装佐柞做谞转揍谞拽滋坐准专最罪祖咨阻