【LeetCode刷题-树】--998.最大二叉树II

998.最大二叉树II

【LeetCode刷题-树】--998.最大二叉树II_第1张图片

【LeetCode刷题-树】--998.最大二叉树II_第2张图片

/**
 * 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) {
        //当前节点值<插入值(或者当前节点为空):插入节点作为当前节点的根,当前节点作为插入节点的左子节点
        if(root == null || val > root.val){
            return new TreeNode(val,root,null);
        }
        //当前节点值>插入值:插入节点递归插入当前节点的右子树
        root.right = insertIntoMaxTree(root.right,val);
        return root;
    }
}

你可能感兴趣的:(#,二叉树,leetcode,算法)