n个节点二叉树有几个指针域

    科技2026-08-08  17

    n个节点二叉树有几个指针域

    Problem Statement: You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL. Initially, all next pointers are set to NULL.

    问题陈述:您将得到一棵完美的二叉树,其中所有叶子都在同一级别,每个父级都有两个孩子。 填充每个下一个指针以指向其下一个右节点。 如果没有下一个右节点,则下一个指针应设置为NULL 。 最初,所有下一个指针都设置为NULL 。

    Example:

    例:

    Code:

    码:

    Explanation:

    说明:

    Above is the iterative approach to the problem.

    上面是解决问题的迭代方法。

    Initialize a queue data structure that would be useful for tree traversal. Initially add root to the queue. Then iterate over each level of the tree.

    初始化将对树遍历有用的队列数据结构。 最初将root添加到队列。 然后遍历树的每个级别。

    Iterate over all the nodes on the current level. Remove the node from the front of the queue. The check (i < size-1) is important as we don’t want to establish any wrong connections. The queue will contain nodes from 2 levels at most at any point in time(since we are adding node’s children to the queue). This check ensures we don’t establish the next pointers beyond the end of the current level.

    遍历当前级别上的所有节点。 从队列的最前面删除该节点。 检查(i <size-1)很重要,因为我们不想建立任何错误的连接。 队列在任何时间点最多包含2个级别的节点(因为我们正在将节点的子级添加到队列中)。 此检查可确保我们不会在当前级别的末尾建立下一个指针。

    Keep adding the children of a node in the queue and so on…

    继续在队列中添加节点的子节点,依此类推……

    In the end return the root of the tree with the next pointers populated.

    最后,返回树的根,并填充下一个指针。

    Complexity Analysis:

    复杂度分析:

    Time Complexity: O(N), N is the number of nodes in the binary tree since we are visiting every node once.

    时间复杂度: O ( N ), N是二叉树中的节点数,因为我们访问每个节点一次。

    Space Complexity: O(N).

    空间复杂度:O(N)。

    Github link to the solution: https://github.com/shivanidwivedi/JavaProgramming/commit/0d9d7ea4fcc889c6f31e3ddd28e8f2b5625a9a57

    Github到解决方案的链接: https : //github.com/shivanidwivedi/JavaProgramming/commit/0d9d7ea4fcc889c6f31e3ddd28e8f2b5625a9a57

    翻译自: https://medium.com/nerd-for-tech/java-populating-next-right-pointers-in-each-node-of-a-binary-tree-f49472975cc2

    n个节点二叉树有几个指针域

    Processed: 0.011, SQL: 9