当前位置:网站首页>LeetCode刷题|897递增顺序搜索树
LeetCode刷题|897递增顺序搜索树
2022-04-23 05:58:00 【杜小瑞】
终于结束了几天的动态规划,迎来了今天这一道简单题。但是仔细一看,这一道跟树相关的简单题好像也没有那么简单,至少对于我来说是这样的。刷了这么久的题,对树的题目做的还是比较少的,正好乘今天好好学一下。
题目描述
题目地址:递增顺序搜索树
解法一
解法一的思想比较简单直接,就是直接中序遍历然后把所有元素存储到一个数组中,然后在从数组中拿出元素重新构建一颗树。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def increasingBST(self, root: TreeNode) -> TreeNode:
def dfs(root: TreeNode, ans: List) -> List:
if root == None:return
dfs(root.left, ans)
ans.append(root.val)
dfs(root.right, ans)
nums = []
dfs(root, nums)
dummynode = TreeNode(-1)
currentnode = dummynode
for i in nums:
currentnode.left = None
currentnode.right = TreeNode(i)
currentnode = currentnode.right
return dummynode.right
这里又用到了哑结点,哑结点在很多跟链表和树有关的题目中都十分有用,可以省去一些复杂的边界判断。
解法二
解法二也是我最开始想到的方法,那就是在中序遍历的过程中直接改变指针的指向。但是我自己没有做出来,看了答案才明白怎么做。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def increasingBST(self, root: TreeNode) -> TreeNode:
dummynode = TreeNode(-1)
self.currentnode = dummynode
self.dfs(root)
return dummynode.right
def dfs(self, node: TreeNode) -> List:
if node == None:return
self.dfs(node.left)
self.currentnode.right = node
node.left = None
self.currentnode = node
self.dfs(node.right)
版权声明
本文为[杜小瑞]所创,转载请带上原文链接,感谢
https://blog.csdn.net/DXRfighting/article/details/116123762
边栏推荐
- Database programming of node
- Leak detection and vacancy filling (III)
- Jenkins搭建与使用
- Promise(二)
- ASP.NET CORE3.1 Identity注册用户后登录失败的解决方案
- Usage of if conditional statements in SQL
- Each traversal usage of tp6
- New type of dark energy could solve Universe expansion mystery
- 【代码解析(3)】Communication-Efficient Learning of Deep Networks from Decentralized Data
- Leak detection and filling (I)
猜你喜欢
Batch modify / batch update the value of a field in the database
2021-09-18
.Net Core 下使用 Quartz —— 【1】快速开始
Binary sum of leetcode questions
tp5 报错variable type error: array解决方法
surprise库中evaluate函数弃用解决方法
js中entries(),keys(),values() , some(), Object.assign()遍历数组用法
Kids and COVID: why young immune systems are still on top
Leak detection and vacancy filling (III)
WebAPI+Form表单上传文件
随机推荐
mysql中sum (if)_mysql 中sum (if())
Leak detection and vacancy filling (V)
Parse PSD files and map them into components
【代码解析(5)】Communication-Efficient Learning of Deep Networks from Decentralized Data
postMan 传参总结
Leak detection and filling (I)
模仿扇贝短文阅读页面
百度地图案例-缩放组件、地图比例组件
Batch modify / batch update the value of a field in the database
C# webpai 路由详解
Scientists say Australian plan to cull up to 10,000 wild horses doesn’t go far enough
Decentralized Collaborative Learning Framework for Next POI Recommendation
JS性能优化
js中的作用域与作用域链
DNA reveals surprise ancestry of mysterious Chinese mummies
浏览器工作原理与实践
leetcode刷题之整数加一
2021-09-18
Color string conversion
TP6 的 each 遍历用法