代码拉取完成,页面将自动刷新
//2种解法 1.循环
// 2.递归
public class _998 {
static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
static class Solution1 {
class Solution {
public TreeNode insertIntoMaxTree(TreeNode root, int val) {
//分情况讨论
//1. 当前节点大于根节点
//2. 当前节点大于根右子树的根
TreeNode cur = new TreeNode(val);
TreeNode right = root;
TreeNode p = null;
while (right != null && right.val > cur.val) {
p = right;
right = right.right;
}
if (p != null) {
p.right = cur;
}
cur.left = right;
return right == root ? cur : root;
}
}
}
static class Solution2 {
public TreeNode insertIntoMaxTree(TreeNode root, int val) {
//递归
// 1. 如果直接插入则返回cur
if (root == null || val > root.val) {
TreeNode cur = new TreeNode(val);
cur.left = root;
return cur;
}
root.right = insertIntoMaxTree(root.right, val);
return root;
}
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。