2020-09-26 力扣中二叉树的创建方法

按照层序遍历创建树

        public void initTree (int[] tree)
        {
            Queue queue = new Queue();
            TreeNode root = new TreeNode(tree[0]);
            queue.Enqueue(root);
            for (int i = 1; i < tree.Length; i++)
            {
                TreeNode currentNode = (TreeNode)queue.Peek();
                if (currentNode.left == null)
                {
                    currentNode.left = new TreeNode(tree[i]);
                    continue;
                }
                if (currentNode.right == null)
                {
                    currentNode.right = new TreeNode(tree[i]);
                }
                if (currentNode.left!=null && currentNode.right!=null)
                {
                    queue.Dequeue();
                    queue.Enqueue(currentNode.left);
                    queue.Enqueue(currentNode.right);
                }
            }
        }

你可能感兴趣的:(2020-09-26 力扣中二叉树的创建方法)