美文网首页
二叉树 Leetcode 897 递增顺序查找树

二叉树 Leetcode 897 递增顺序查找树

作者: 禾木清清 | 来源:发表于2019-07-14 19:53 被阅读0次

题目

给定一个树,按中序遍历重新排列树,使树中最左边的结点现在是树的根,并且每个结点没有左子结点,只有一个右子结点。

示例 :

输入:[5,3,6,2,4,null,8,1,null,null,null,7,9]

   5
  / \
3    6

/ \
2 4 8
/ / \
1 7 9

输出:[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

提示:

给定树中的结点数介于 1 和 100 之间。
每个结点都有一个从 0 到 1000 范围内的唯一整数值。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/increasing-order-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路

  • 使用递归获得中序遍历值
  • 从头开始建树

代码

# 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):
    def increasingBST(self, root):
        """
        :type root: TreeNode
        :rtype: TreeNode
        """
        def inorder(root):
            if not root:
                return None
            res = []
            
            if root.left:
                res.extend(inorder(root.left))
            res.append(root.val)
            
            if root.right:
                res.extend(inorder(root.right))
            
            return res
        
        res = inorder(root)
        head = curr = TreeNode(0)
        
        for t in res:
            curr.right = TreeNode(t)
            curr = curr.right
        
        return head.right

相关文章

  • LeetCode 897. 递增顺序查找树

    897. 递增顺序查找树 给定一个树,按中序遍历重新排列树,使树中最左边的结点现在是树的根,并且每个结点没有左子结...

  • LeetCode-897. 递增顺序查找树

    给你一个树,请你 按中序遍历 重新排列树,使树中最左边的结点现在是树的根,并且每个结点没有左子结点,只有一个右子结...

  • leetcode 897. 递增顺序查找树

    见注释

  • 二叉树 Leetcode 897 递增顺序查找树

    题目 给定一个树,按中序遍历重新排列树,使树中最左边的结点现在是树的根,并且每个结点没有左子结点,只有一个右子结点...

  • 897.递增顺序查找树

    题目#897.递增顺序查找树 给定一个树,按中序遍历重新排列树,使树中最左边的结点现在是树的根,并且每个结点没有左...

  • 897. 递增顺序查找树

    1. 问题 Given a tree, rearrange the tree in in-order so tha...

  • LeetCode题解之递增顺序查找树

    递增顺序查找树 题目描述 给你一个树,请你 按中序遍历 重新排列树,使树中最左边的结点现在是树的根,并且每个结点没...

  • 递增顺序查找树

    题目: 题目的理解: 中序遍历二叉树,获取到的值来创建TreeNode。 python实现 提交 // END 多...

  • 897. 递增顺序搜索树

    描述 给你一棵二叉搜索树,请你 按中序遍历 将其重新排列为一棵递增顺序搜索树,使树中最左边的节点成为树的根节点,并...

  • LeetCode.897-递增搜索树(Increasing Or

    这是悦乐书的第346次更新,第370篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第...

网友评论

      本文标题:二叉树 Leetcode 897 递增顺序查找树

      本文链接:https://www.haomeiwen.com/subject/trmikctx.html