998. Maximum Binary Tree II(最大二叉树II)

本文探讨了在最大二叉树中插入新节点的两种方法:迭代和递归。详细解析了为何新节点总是在右侧插入,以及如何在保持树特性的同时找到正确的位置。通过代码示例展示了具体实现。

题目描述

在这里插入图片描述在这里插入图片描述在这里插入图片描述

方法思路

Q1:Why to the right and not to the left?
Always go right since new element will be inserted at the end of the list.
Q2:why if(root.val<v){
TreeNode node = new TreeNode(v);
node.left=root;
return node;
},rather than if(root.val<v){
TreeNode node = new TreeNode(v);
node.right=root;
return node;
};
Is it just follow the example?

Approach1: iterative
Search on the right, find the node that cur.val > val > cur.right.val
Then create new node TreeNode(val),
put old cur.right as node.left,
put node as new cur.right.

public TreeNode insertIntoMaxTree(TreeNode root, int val) {
        TreeNode node = new TreeNode(val), cur = root;
        if (root.val < val) {
            node.left = root;
            return node;
        }
        while (cur.right != null && cur.right.val > val) {
            cur = cur.right;
        }
        node.left = cur.right;
        cur.right = node;
        return root;
    }

Approach2:recursive
这道题目描述的不是很清楚感觉上。(tricky!)
The idea is to insert node to the right parent or right sub-tree of current node. Using recursion can achieve this:
If inserted value is greater than current node, the inserted goes to right parent
If inserted value is smaller than current node, we recursively re-cauculate right subtree

class Solution {
	//Runtime: 2 ms, faster than 100.00%
    //Memory Usage: 37 MB, less than 100.00% 
    public TreeNode insertIntoMaxTree(TreeNode root, int v) {
        if(root==null)return new TreeNode(v);
        if(root.val<v){
            TreeNode node = new TreeNode(v);
            node.left=root;
            return node;
        }
        root.right=insertIntoMaxTree(root.right,v);
        return root;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值