当前位置:网站首页>897. Increasing Order Search Tree
897. Increasing Order Search Tree
2022-08-09 07:57:00 【scwMason】
Given a tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only 1 right child.
Example 1: Input: [5,3,6,2,4,null,8,1,null,null,null,7,9] 5 / \ 3 6 / \ \ 2 4 8 / / \ 1 7 9 Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9] 1 \ 2 \ 3 \ 4 \ 5 \ 6 \ 7 \ 8 \ 9
Note:
- The number of nodes in the given tree will be between 1 and 100.
- Each node will have a unique integer value from 0 to 1000.
意思就是把就是按照先序遍历重新构成一个只有右子树的树
思路:
先创建一个空的头节点node,再定义一个指向node的tree(当前节点)然后递归遍历,直到碰到递归边界,就return,然后把当前节点放到tree的右子树上,并让tree重新指向自己的右子树,这样一层一层下来就行了
代码
class Solution:
tree=TreeNode(None)#头指针
node=tree#当前节点
def increasingBST(self, root: TreeNode) -> TreeNode:
if not root:#如果到递归边界
return
self.increasingBST(root.left)#遍历左子树
self.node.right=TreeNode(root.val)#创建节点放到当前
self.node=self.node.right#移动当前节点
self.increasingBST(root.right)#向右递归
return self.tree.right
边栏推荐
猜你喜欢
随机推荐
BGP路由协议的那些事?(中)
SDRAM的数据存储实现并对其数据进行读写操作
贪吃蛇小游戏——C语言
Kotlin Coroutines - Exception Handling
LeetCode: 876. The middle node of the linked list —— simple
原生JDBC操作数据库
C#高级学习1
毕业我选择了保家卫国,退伍我选择了华为外包
LeetCode·每日一题·636.函数的独占时间·栈模拟
我的创作纪念日
3D软件开发工具HOOPS全套产品开发介绍 | HOOPS Visualize、HOOPS Publish
Use tensorflow.keras to build a neural network model modularly
Snake game, C language
Shell--常用小工具(sort、uniq、tr、cut)
一站制造项目及Spark核心面试 ,220808,,,
yolov5检测数据集标签数量
C语言:打印菱形
3D精彩案例,清软英泰建成综合轻量化显示平台!
HOOPS是什么?这4款3D软件开发工具包你还不知道?
Collection 接口 & List 接口