如何在二叉树中添加节点

发布于 2024-08-30 08:33:52 字数 148 浏览 1 评论 0原文

<前><代码> (5)根 (3)-----^--------(7) (2)---^----(5) ^-----(8)

我想在此二叉搜索树中添加数据为 5 的节点。请帮忙。

                   (5)Root
          (3)-------^--------(7)
     (2)---^----(5)           ^-----(8)

I want to add node with data 5 in this binary Search tree. Please help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

幸福%小乖 2024-09-06 08:33:52

注意:这个答案假设您正在谈论二叉搜索树。

从根开始遍历二叉树:

  • 如果新元素小于或等于当前节点,则转到左子树,否则转到右子树并继续遍历
  • 如果到达一个节点,则可以在其中不要再深入了,因为没有子树,这是插入新元素的地方

    <前><代码> (5)根
    (3)-----^--------(7)
    (2)---^----(5) ^-----(8)
    (5)--^

你从(5),然后向左(因为 5 <= 5)到 (3),然后向右(因为 5 > 3)到 (5),然后你想要转到左子树(因为 5 <= 5),但是您看到没有子树,因此这是插入新元素 (5) 的位置。

Note: This answer assumes you are talking about a binary search tree.

You traverse the binary tree from the root:

  • if your new element is less or equal than the current node, you go to the left subtree, otherwise to the right subtree and continue traversing
  • if you arrived at a node, where you can not go any deeper, because there is no subtree, this is the place to insert your new element

                   (5)Root
          (3)-------^--------(7)
     (2)---^----(5)           ^-----(8)
            (5)--^
    

You start at (5), then go left (since 5 <= 5) to (3), then go right (since 5 > 3) to (5), then you want to go to the left subtree (since 5 <= 5), but you see that there is no subtree, so this is the place to insert your new element (5).

远昼 2024-09-06 08:33:52

这取决于您是否想要保持二叉树:

  • 排序
  • 平衡

如果这两个都不是要求,那么添加元素的最快方法是将其作为新根,并使树的其余部分具有其子元素之一

                         (5)
                   (5)----^
          (3)-------^--------(7)
     (2)---^----(5)           ^-----(8)

:二叉搜索树不应该有重复的值,并且插入过程更复杂,需要遍历树来找到插入点。请参阅此处

对于自平衡二叉搜索树,它甚至更加复杂,例如可能涉及执行树旋转 。请参阅此处了解更多详细信息。

It depends on whether you want to keep your binary tree:

  • sorted
  • balanced

If neither of these are requirements then the fastest way to add an element is to put it as the new root and have the rest of the tree has one of its children:

                         (5)
                   (5)----^
          (3)-------^--------(7)
     (2)---^----(5)           ^-----(8)

For binary search trees you should not have repeated values and the process for insertion is more complicated and requires traversing the tree to find the insertion point. See here.

For self-balancing binary search trees it is even more complicated and can for example involve performing tree rotations. See here for more details.

热情消退 2024-09-06 08:33:52
private void Insert(Node node, ref Node tree)
{    
        if (tree == null)                          // Found a leaf?    
        {                                      
             tree = node;                          // Found it! Add the new node as the new leaf.
        }    
        else    
        {        
             int val = string.Compare(node.Key, tree.Key);        // already inserted        
             if (val == 0)
             {            
                  throw new InvalidOperationException("Duplicate key");
             }        
             elseif (val < 0)        
             {            
                  Node left = tree.Left;            
                  Insert(node, ref left);              // Keep moving down the left side.            
                  tree.Left = left;        
             }        
             else        
             {            
                  Node right = tree.Right;         
                  Insert(node, ref right);            // Keep moving down the right side.            
                  tree.Right = right;        
             }    
      }
}
private void Insert(Node node, ref Node tree)
{    
        if (tree == null)                          // Found a leaf?    
        {                                      
             tree = node;                          // Found it! Add the new node as the new leaf.
        }    
        else    
        {        
             int val = string.Compare(node.Key, tree.Key);        // already inserted        
             if (val == 0)
             {            
                  throw new InvalidOperationException("Duplicate key");
             }        
             elseif (val < 0)        
             {            
                  Node left = tree.Left;            
                  Insert(node, ref left);              // Keep moving down the left side.            
                  tree.Left = left;        
             }        
             else        
             {            
                  Node right = tree.Right;         
                  Insert(node, ref right);            // Keep moving down the right side.            
                  tree.Right = right;        
             }    
      }
}
三寸金莲 2024-09-06 08:33:52
/// <summary>
    /// Construct the tree from a pre order traversal
    /// </summary>
    /// <param name="preorderTraversal"></param>
    /// <returns></returns>
    public static TreeNode ConstructTreeFromPreOrderTraversal(int[] preorderTraversal)
    {

        if (null == preorderTraversal || preorderTraversal.Length < 1)
            return null;
        TreeNode root = null;
        int len = preorderTraversal.Length;
        for (int i = 0; i < len; i++)
        {
            TreeNode newNode = new TreeNode();
            newNode.Data = preorderTraversal[i];
            newNode.Left = newNode.Right = null;
            AddNode(ref root, newNode);
        }
        return root;
    }

    /// <summary>
    /// add not in the tree
    /// </summary>
    /// <param name="root"></param>
    /// <param name="newNode"></param>
    private static void AddNode(ref TreeNode root, TreeNode newNode)
    {
        if (root == null)
            root = newNode;
        else if (newNode.Data < root.Data)
        {
            TreeNode left = root.Left;
            AddNode(ref left, newNode);
            root.Left = left;
        }
        else
        {
            TreeNode right = root.Right;
            AddNode(ref right, newNode);
            root.Right = right;
        }
    }
/// <summary>
    /// Construct the tree from a pre order traversal
    /// </summary>
    /// <param name="preorderTraversal"></param>
    /// <returns></returns>
    public static TreeNode ConstructTreeFromPreOrderTraversal(int[] preorderTraversal)
    {

        if (null == preorderTraversal || preorderTraversal.Length < 1)
            return null;
        TreeNode root = null;
        int len = preorderTraversal.Length;
        for (int i = 0; i < len; i++)
        {
            TreeNode newNode = new TreeNode();
            newNode.Data = preorderTraversal[i];
            newNode.Left = newNode.Right = null;
            AddNode(ref root, newNode);
        }
        return root;
    }

    /// <summary>
    /// add not in the tree
    /// </summary>
    /// <param name="root"></param>
    /// <param name="newNode"></param>
    private static void AddNode(ref TreeNode root, TreeNode newNode)
    {
        if (root == null)
            root = newNode;
        else if (newNode.Data < root.Data)
        {
            TreeNode left = root.Left;
            AddNode(ref left, newNode);
            root.Left = left;
        }
        else
        {
            TreeNode right = root.Right;
            AddNode(ref right, newNode);
            root.Right = right;
        }
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文