[leetcode] 998. Maximum Binary Tree II

Description

We are given the root node of a maximum tree: a tree where every node has a value greater than any other value in its subtree.

Just as in the previous problem, the given tree was constructed from an list A (root = Construct(A)) recursively with the following Construct(A) routine:

  • If A is empty, return null.
  • Otherwise, let A[i] be the largest element of A. Create a root node with value A[I].
  • The left child of root will be Construct([A[0], A[1], …, A[i-1]])
  • The right child of root will be Construct([A[i+1], A[i+2], …, A[A.length - 1]])
  • Return root.
    Note that we were not given A directly, only a root node root = Construct(A).

Suppose B is a copy of A with the value val appended to it. It is guaranteed that B has unique values.

Return Construct(B).

Example 1:

Input: root = [4,1,3,null,null,2], val = 5
Output: [5,4,null,1,3,null,null,2]
Explanation: A = [1,4,2,3], B = [1,4,2,3,5]

Example 2:

Input: root = [5,2,4,null,1], val = 3
Output: [5,2,4,null,1,null,3]
Explanation: A = [2,1,5,4], B = [2,1,5,4,3]

Example 3:

Input: root = [5,2,3,null,1], val = 4
Output: [5,2,4,null,1,3]
Explanation: A = [2,1,5,3], B = [2,1,5,3,4]

Constraints:

  • 1 <= B.length <= 100

分析

题目的意思是:给你一颗最大二叉树,其中根结点是最大值。这道题我用递归的方法试了一下,发现总是有case ac不了。这里借鉴了别人的解法,如果为空,则直接建立一个结点并返回就行了。如果当前节点的值小于给定的val,说明找到了要插入的地方,创建一个结点t,t的左结点指向当前的结点,然后返回就行了。其他的就向右递归遍历就行了,不要问我为啥要一直向右递归,其实我也想知道,哈哈哈。我目测是找规律发现插入的位置都在右边,所以…

代码

# 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 insertIntoMaxTree(self, root: TreeNode, val: int) -> TreeNode:
        if(root is None):
            return TreeNode(val)
        if(val>root.val):
            t=TreeNode(val)
            t.left=root
            return t
        root.right=self.insertIntoMaxTree(root.right,val)
        return root

参考文献

[LeetCode] fast simple and easy in py3

猜你喜欢

转载自blog.csdn.net/w5688414/article/details/109267501