# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
#
# @param root TreeNode类 the root
# @return int整型一维数组
#
class Solution:
### 法一:递归
def dfs(self,root,temp_list):
if root: # 中序遍历
self.dfs(root.left, temp_list)
temp_list.append(root.val)
self.dfs(root.right, temp_list)
def findError(self , root ):
# write code here
temp_list = []
self.dfs(root,temp_list)
res = []
# 顺序寻找第一个错误位置
for i in range(len(temp_list)):
if temp_list[i]>temp_list[i+1]:
res.append(i+1)
break
# 逆序寻找第二个错误位置
for i in range(len(temp_list)-1,-1,-1):
if temp_list[i]<temp_list[i-1]:
res.append(i+1)
break
return res
### 法二:迭代
def findError(self , root ):
# write code here
res = [None, None]
arr = self.inOrder(root)
ii = -1
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
res[1] = arr[i]
ii = i
break
for j in range(len(arr) - 1, ii, -1):
if arr[j] < arr[j - 1]:
res[0] = arr[j]
break
return res
def inOrder(self, root):
res = []
if not root:
return res
stk = []
p = root
while p or stk:
while p:
stk.append(p)
p = p.left
node = stk.pop()
res.append(node.val)
p = node.right
return res
二叉搜索树中两个【交换位置】的节点
于 2021-06-16 00:40:27 首次发布