向二叉树中插入元素

[!Tip]

本节源代码见Github链接🔗


问题描述

向二叉树中插入一个元素


核心思路

层次遍历树,只要结点没有两个子结点即可插入


实现代码

【👉🏻>>点击展开查看代码】
        
        /**  
         * 向二叉树中插入元素  
         *  
         * @className: InsertInBinaryTree  
         * @author: Max Solider  
         * @date: 2023-06-11 16:16  
         */public class InsertInBinaryTree {  

            public static void insertInBinaryTree(BinaryTreeNode node, BinaryTreeNode root) {  
                if (root == null || node == null) {  
                    return;  
                }  
                ArrayQueue queue = new ArrayQueue(20);  
                queue.enQueue(root);  
                while (!queue.isEmpty()) {  
                    BinaryTreeNode tmp = (BinaryTreeNode)queue.deQueue();  
                    if (tmp.getLeft() == null) {  
                        tmp.setLeft(node);  
                        return;            }  
                    if (tmp.getRight() == null) {  
                        tmp.setRight(node);  
                        return;            }  
                    if (tmp.getLeft() != null) {  
                        queue.enQueue(tmp.getLeft());  
                    }  
                    if (tmp.getRight() != null) {  
                        queue.enQueue(tmp.getRight());  
                    }  
                }  
            }  
        }
        
    

时间复杂度

时间复杂度为O(n)


空间复杂度

空间复杂度为O(n)


© MaxSolider all right reserved,powered by Gitbook文件修订时间: 2023-06-11 16:24:16

results matching ""

    No results matching ""