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