48 Insert into a Binary Search Tree

題目

Given the root node of a binary search tree (BST) and a value to be inserted into the tree, insert the value into the BST. Return the root node of the BST after the insertion. It is guaranteed that the new value does not exist in the original BST.

Note that there may exist multiple valid ways for the insertion, as long as the tree remains a BST after insertion. You can return any of them.

For example,

Given the tree:

    4
   / \
  2   7
 / \
1   3

And the value to insert: 5

You can return this binary search tree:

     4
   /   \
  2     7
 / \   /
1   3 5

This tree is also valid:

     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);
        if(val>root.val)
            root.right = insertIntoBST(root.right,val);
        else
            root.left = insertIntoBST(root.left,val);
        return root;
    }
}

在這裏插入圖片描述

速度可以,但是遞歸非常耗內存。
去瞅瞅別人的解法。

拆開遞歸運行性能也差不多,這裏貼出來作爲參考。

    public TreeNode insertIntoBST(TreeNode root, int val) {
        if(root == null) return new TreeNode(val);
        TreeNode cur = root;
        while(true) {
            if(cur.val <= val) {
                if(cur.right != null) cur = cur.right;
                else {
                    cur.right = new TreeNode(val);
                    break;
                }
            } else {
                if(cur.left != null) cur = cur.left;
                else {
                    cur.left = new TreeNode(val);
                    break;
                }
            }
        }
        return root;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章