package com.算法专练.力扣.最大二叉树II;
/**
* @author xnl
* @Description:
* @date: 2022/8/30 22:32
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
}
/**
* 模拟题,根据题目描述,添加节点之后添加大右子树上面去,所以只需要一直遍历右子树就行
* @param root
* @param val
* @return
*/
public TreeNode insertIntoMaxTree(TreeNode root, int val) {
// 父节点
TreeNode parentNode = null;
// 当前节点
TreeNode cur = root;
while (cur != null){
if (cur.val < val){
if (parentNode == null){
// 如果大于跟节点,那么就替换为根节点
return new TreeNode(val, root, null);
}
TreeNode treeNode = new TreeNode(val, cur, null);
parentNode.right = treeNode;
return root;
} else {
parentNode = cur;
cur = cur.right;
}
}
parentNode.right = new TreeNode(val);
return root;
}
}
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;
}
}
力扣:998. 最大二叉树 II
最新推荐文章于 2024-11-04 12:20:00 发布