《LeetCode力扣练习》代码随想录——二叉树(二叉搜索树中的插入操作—Java)
刷题思路来源于 代码随想录
701. 二叉搜索树中的插入操作
-
二叉树-递归
/** * 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 insertIntoBST(TreeNode root, int val) { return recursion(root, val); } private TreeNode recursion(TreeNode root, int val) { if (root == null) { return new TreeNode(val); } if (val < root.val) { root.left = recursion(root.left, val); } if (val > root.val) { root.right = recursion(root.right, val); } return root; } }