leetcode 998 3种解法个人总结

/**
 * Definition for a binary tree node.
 * public 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;
 *     }
 * }
 */
class Solution {
    //方法一:在原树的基础上构建新的树
    public TreeNode insertIntoMaxTree(TreeNode root, int val) {
        TreeNode curr  = root;
        TreeNode parent = new TreeNode();
        TreeNode dummy = parent;
        parent.right = root;
        while(parent != null){
            if(curr == null || val >= curr.val){
                TreeNode insertNode = new TreeNode(val);
                insertNode.left = curr;
                parent.right = insertNode;
                return dummy.right;
            }else{
                parent = curr;
                curr = curr.right;
            }
        }
        return dummy.right;
    }
}

class Solution {
    //方法二:先根据原树生成列表a,由列表a生成列表b,再由b构建新的树
    int index = 0;
    public TreeNode insertIntoMaxTree(TreeNode root, int val) {
        int [] map = new int[101];
        mapToArray(root,map);
        map[index] = val;
        return buildTree(map,0,index);
    }

    public void mapToArray(TreeNode root, int [] map){
        if(root == null){
            return;
        }
        mapToArray(root.left,map);
        map[index++] = root.val;
        mapToArray(root.right,map);
    }

    public TreeNode buildTree(int [] map,int start,int end){
        if(start > end){
            return null;
        }
        int ans = start;
        int max = map[start];
        for(int i = start+1;i <= end;++i){
            if(map[i] > max){
                ans = i;
                max = map[i];
            }
        }
        TreeNode root = new TreeNode(map[ans]);
        root.left = buildTree(map,start,ans-1);
        root.right = buildTree(map,ans+1,end);
        return root;
    }
}
class Solution {
    //方法三:方法一的递归版
    public TreeNode insertIntoMaxTree(TreeNode root, int val) {
        if(root == null || val >= root.val){
            TreeNode insertNode = new TreeNode(val);
            insertNode.left = root;
            return insertNode;
        }else{
            root.right = insertIntoMaxTree(root.right,val);
        }
        return root;
    }
}
作者:Coder_Jenny
链接:https://leetcode.cn/problems/maximum-binary-tree-ii/solution/by-coder_jenny-g73d/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值