【leetcode】897. Increasing Order Search Tree
题目如下:
解题思路:我的方法是先用递归的方法找出最左边的节点,接下来再对树做一次递归中序遍历,找到最左边节点后将其设为root,其余节点依次插入即可。
代码如下:
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): newRoot = None current = None leftMost = 0 def traverse(self,node): if node.val == self.leftMost: self.newRoot = TreeNode(node.val) self.current = self.newRoot if node.left != None: self.traverse(node.left) #self.leftMost = node.left.val if self.current != None and node.val != self.leftMost: self.current.right = TreeNode(node.val) self.current = self.current.right if node.right != None: self.traverse(node.right) def increasingBST(self, root): """ :type root: TreeNode :rtype: TreeNode """ if root == None: return root r = root while r != None: self.leftMost = r.val r = r.left self.newRoot = None self.current = None self.traverse(root) return self.newRoot