lintcode 容易题:Insert Node in a Binary Search Tree 在二叉查找树中插入节点

题目:

 在二叉查找树中插入节点

给定一棵二叉查找树和一个新的树节点,将节点插入到树中。

你需要保证该树仍然是一棵二叉查找树。

 样例

给出如下一棵二叉查找树,在插入节点6之后这棵二叉查找树可以是这样的:

挑战

能否不使用递归?

解题:

递归的方法比较简单

Java程序:

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
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(root.val>=node.val)
            root.left = insertNode(root.left,node);
        if(root.val<node.val)
            root.right = insertNode(root.right,node);
        return root;
    }
}

总耗时: 1636 ms

非递归的感觉比较复杂。。。。

一直非递归的方法,就是一直走,一直走,走到没有路的时候就是插入的节点,这里是因为插入的节点一定是在新建的叶子节点,原理是二叉查找树是;1,根节点左子树的值比根节点小,右子树的值都比根节点大,2.左右子树也满足1的条件

下面程序定义的last指针是用来做最后插入节点的父节点的

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
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){
             root=node;
             return root;
        }
        TreeNode cur = root;
        TreeNode last = null;
        while(cur!=null){
            last = cur;
            if(cur.val>node.val){
                cur = cur.left;
            }else{
                cur = cur.right;
            }
        }
        if(last!=null){
            if(last.val>node.val){
                last.left = node;
            }else{
                last.right = node;
            }
        }
        return root;
    }
}

总耗时: 1753 ms

Python程序:

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""
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.
    """
    def insertNode(self, root, node):
        # write your code here
        if root==None:
            return node
        if root.val>=node.val:
            root.left = self.insertNode(root.left,node)
        if root.val<node.val:
            root.right = self.insertNode(root.right,node)
        return root
        

总耗时: 272 ms

非递归程序:

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""
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.
    """
    def insertNode(self, root, node):
        # write your code here
        cur = root
        last = None
        if root==None:
            return node
        while cur!=None:
            last = cur
            if cur.val>node.val:
                cur = cur.left
            elif cur.val<=node.val:
                cur = cur.right
        if last!=None:
            if last.val>node.val:
                last.left = node
            else:
                last.right = node
        return root

时间: 2024-12-28 13:14:50

lintcode 容易题:Insert Node in a Binary Search Tree 在二叉查找树中插入节点的相关文章

[Lintcode] Insert Node in a Binary Search Tree

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, after Insert node 6, the tree

[lintcode easy]Insert Node in a Binary Search Tree

Insert Node in a Binary Search Tree Example Given binary search tree as follow, after Insert node 6, the tree should be: 2 2 / \ / 1 4 --> 1 4 / / \ 3 3 6 Challenge Can you do it without recursion? /** * Definition of TreeNode: * public class TreeNod

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 Challeng

LeetCode 501. Find Mode in Binary Search Tree(寻找二叉查找树中出现次数最多的值)

题意:寻找二叉查找树中出现次数最多的值 /** * 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: int ma = 0; int cnt = 1; TreeNode

LintCode(85)在二叉查找树中插入节点

题目 在二叉查找树中插入节点 给定一棵二叉查找树和一个新的树节点,将节点插入到树中. 你需要保证该树仍然是一棵二叉查找树. 样例 给出如下一棵二叉查找树,在插入节点6之后这棵二叉查找树可以是这样的: 2 2 / \ / 1 4 --> 1 4 / / \ 3 3 6 分析 递归和非递归两种方法实现. Python代码 """ Definition of TreeNode: class TreeNode: def __init__(self, val): self.val

LintCode 85. 在二叉查找树中插入节点

题目: 给定一棵二叉查找树和一个新的树节点,将节点插入到树中. 你需要保证该树仍然是一棵二叉查找树 样例 给出如下一棵二叉查找树,在插入节点6之后这棵二叉查找树可以是这样的: 2 2 / \ / 1 4 --> 1 4 / / \ 3 3 6 挑战 能否不使用递归? /** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val)

501. Find Mode in Binary Search Tree查找BST中的众数

[抄题]: Given a binary search tree (BST) with duplicates, find all the mode(s) (the most frequently occurred element) in the given BST. Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than or equal to t

99. Recover Binary Search Tree -- 找到二叉排序树中交换过位置的两个节点

Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Note:A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? /** * Definition for a binary

PAT甲题题解1099. Build A Binary Search Tree (30)-二叉树遍历

题目就是给出一棵二叉搜索树,已知根节点为0,并且给出一个序列要插入到这课二叉树中,求这棵二叉树层次遍历后的序列. 用结构体建立节点,val表示该节点存储的值,left指向左孩子,right指向右孩子.中序遍历的顺序正好是序列从小到大的顺序,因此中序遍历的时候顺便赋值就可以了,最后层次遍历输出. 思路一:中序遍历的时候赋值 #include <iostream> #include <cstdio> #include <algorithm> #include <str