构造最大数,题目的意思是
给出一个序列A按照题目的构造方法给出一个树,
现在在序列A的最后加一个树,求现在的树的样子
sol:
首先加的树是在序列最后,所以应该是去递归树的右边,找到对应的位置后,
注意到最后加的数在最后,所以应该是该位置的右子树,然后比它小的数在它左边,应为它的左子树
需要多想一下。
递归版:
public TreeNode insertIntoMaxTree(TreeNode root, int val) {
if (root != null && val < root.val) {
root.right = insertIntoMaxTree(root.right, val);
return root;
}
TreeNode r = new TreeNode(val);
r.left = root;
return r;
}
迭代版:
public TreeNode insertIntoMaxTree(TreeNode root, int val) {
TreeNode node = new TreeNode(val);
TreeNode k = root;
if (root != null && val > root.val) {
node.left = root;
return node;
}
while (root.right != null && val < root.right.val) {
root = root.right;
}
node.left = root.right;
root.right = node;
return k;
}