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, returnnull
. - Otherwise, let
A[i]
be the largest element ofA
. Create a root node with valueA[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)
.
最大树定义:一个树,其中每个节点的值都大于其子树中的任何其他值。
给出最大树的根节点 root
。
就像之前的问题那样,给定的树是从表 A(root = Construct(A))
递归地使用下述 Construct(A)
例程构造的:
- 如果
A
为空,返回null
- 否则,令
A[i]
作为A
的最大元素。创建一个值为A[i]
的根节点root
root
的左子树将被构建为 Construct([A[0], A[1], ..., A[i-1]]
)root
的右子树将被构建为 Construct([A[i+1], A[i+2], ..., A[A.length - 1]]
)- 返回
root
请注意,我们没有直接给定 A
,只有一个根节点 root = Construct(A)
.
假设 B
是 A
的副本,并附加值 val
。保证 B
中的值是不同的。
返回 Construct(B)
。
题目链接:https://leetcode.com/problems/maximum-binary-tree-ii/
Difficulty: medium
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]
Note:
- 1 <= B.length <= 100
分析
- 由题意知,对于任意子树,根节点大于所有子节点,且每次插入的节点中序遍历序列的尾部,则节点x应插入到某节点a的右子树上(a的值大于x的值),当前位置子树移到a的左子树上;
- 若x大于root的值,则x左根节点,root左x的左子树;
- 找到ro1、ro2,其中ro1的值大于x的值,ro2的值小于x的值,ro2是ro1的右子树,x做ro1的右节点,ro2做x的左节点;
- 若ro2为None,x做ro1的右节点;
- 返回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):
def insertIntoMaxTree(self, root, val):
p=TreeNode(val)
if(root==None):
return p
if(val>=root.val):
p.left=root
return p
ro1=root
ro2=ro1.right
while(ro2!=None):
if(val>ro2.val):
ro1.right=p
p.left=ro2
return root
else:
ro1=ro2
ro2=ro1.right
ro1.right=p
return root