Insert Node in a Binary Search Tree

Posted apanda009

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Insert Node in a Binary Search Tree相关的知识,希望对你有一定的参考价值。

Given a binary search tree  and a new tree node, insert the node into the tree. You should keep the tree still be a valid binary search tree.

Example
Given binary search tree as follow:

  /           4

         /   


after Insert node 6, the tree should be:

  /           4

         /   \ 
       6

Challenge
Do it without recursion

Iterative做法

public TreeNode insertNode(TreeNode root, TreeNode node) {
        // write your code here
        if (root == null) {
            return node;
        }
        // tmp 不断比较找到最后一个点, 用last记录
        TreeNode tmp = root, last = null;
        while (tmp != null) {
            last = tmp; 
            if (tmp.val > node.val) {
                tmp = tmp.left;
            } else {
                tmp = tmp.right;
            }
            
        }
        // 分情况讨论 将node 链接
        
        if (last.val > node.val) {
                last.left = node;
            } else {
                last.right = node;
            }
        return root;
}

  

分治法:

public TreeNode insertNode(TreeNode root, TreeNode node) {
        if (root == null) {
            return node;
        }
        
        if (root.val > node.val) {
            root.left = insertNode(root.left, node);
        } else {
            root.right = insertNode(root.right, node);
        }
        
        return root;
    }

Recursion做法:

public class Solution {
    /**
     * @param root: The root of the binary search tree.
     * @param node: insert this node into the binary search tree
     * @return: The root of the new binary search tree.
     */
    public TreeNode insertNode(TreeNode root, TreeNode node) {
        // write your code here
        if (root == null) return node;
        if (node == null) return root;
        helper(root, node);
        return root;
    }
    
    public void helper(TreeNode root, TreeNode node) {
        if (root.val <= node.val && root.right == null) root.right = node;
        else if (root.val > node.val && root.left == null) root.left = node;
        else if (root.val <= node.val) helper(root.right, node);
        else helper(root.left, node);
    }
}

  

 

以上是关于Insert Node in a Binary Search Tree的主要内容,如果未能解决你的问题,请参考以下文章

lintcode-easy-Insert Node in a Binary Search Tree

671. Second Minimum Node In a Binary Tree

671. Second Minimum Node In a Binary Tree

[LeetCode] Second Minimum Node In a Binary Tree

[leetcode-671-Second Minimum Node In a Binary Tree]

LeetCode 671. Second Minimum Node In a Binary Tree