链接:https://leetcode-cn.com/problems/maximum-binary-tree-ii/
这道题理解了题目之后就不难做。三种情况:
(1) root 为null,此时返回val单节点构成的树
(2)root的值小于val,以val为根,root接在val的左子树上(必须是左子树)
(3)root的值大于val,进入root的右子树递归(必须是右子树)
java代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode insertIntoMaxTree(TreeNode root, int val) {
if(root == null)
return new TreeNode(val);
if(val>root.val)
{
TreeNode head = new TreeNode(val);
head.left = root;
return head;
}
root.right = insertIntoMaxTree(root.right,val);
return root;
}
}
本文解析了LeetCode上的最大二叉树II问题,介绍了三种情况下的插入操作:当根节点为空、根节点值小于插入值以及根节点值大于插入值时的处理策略。并提供了详细的Java代码实现。
1041

被折叠的 条评论
为什么被折叠?



