1. 程式人生 > >Leetcode 701. 二叉搜索樹中的插入操作

Leetcode 701. 二叉搜索樹中的插入操作

二叉搜索樹 else ini http fin nod 根節點 保持 節點

題目鏈接

https://leetcode.com/problems/insert-into-a-binary-search-tree/description/

題目描述

給定二叉搜索樹(BST)的根節點和要插入樹中的值,將值插入二叉搜索樹。 返回插入後二叉搜索樹的根節點。 保證原始二叉搜索樹中不存在新值。

註意,可能存在多種有效的插入方式,只要樹在插入後仍保持為二叉搜索樹即可。 你可以返回任意有效的結果。

例如,

給定二叉搜索樹:

        4
       /       2   7
     /     1   3

和 插入的值: 5

你可以返回這個二叉搜索樹:

         4
       /         2     7
     / \   /
    1   3 5

或者這個樹也是有效的:

         5
       /         2     7
     / \   
    1   3
                   4

題解

二叉搜索樹的插入,依次遍歷二叉樹,找到插入節點的位置,插入即可。

代碼


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode insertIntoBST(TreeNode root, int val) {
        if (root == null) { return new TreeNode(val); }
        TreeNode cur = root;
        TreeNode pre = null;
        while (cur != null) {
            pre = cur;
            if (cur.val > val) {
                cur = cur.left;
                if (cur == null) {
                    pre.left = new TreeNode(val);
                }
            } else {
                cur = cur.right;
                if (cur == null) {
                    pre.right = new TreeNode(val);
                }
            }
        }
        return root;
    }
}

Leetcode 701. 二叉搜索樹中的插入操作