701. Insert into a Binary Search Tree

Link: https://leetcode.com/problems/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

題目翻譯:

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

請注意,只要樹在插入後仍為 BST,就可能存在多種有效的插入方式。你可以退回任何一個。

程式思路:

簡單的二元素搜索,插入值比較大就往右子樹,比較小就往左子樹,一樣的話就表示樹已有此值直接退出,沒的話就繼續直到,找到空指標時就做插入的動作。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* insertIntoBST(TreeNode* root, int val) {
        if(root == nullptr)
        {
            root = new TreeNode(val);
            return root;
        }
        TreeNode* node = root;
        while(node)
        {
            if(node->val < val)
            {
                if(node->right == nullptr)
                {
                    node->right= new TreeNode(val);
                    break;
                }else
                    node = node->right;
            }
            else if(node->val > val)
            {
                if(node->left == nullptr)
                {
                    node->left= new TreeNode(val);
                    break;
                }else
                    node = node->left;
            }
            else
                break;
        }
        return root;
    }
};

  目錄