zoukankan      html  css  js  c++  java
  • LeetCode117填充每个节点的下一个右侧节点指针 II

    填充每个节点的下一个右侧节点指针 II

    题目描述:给定一个二叉树:

    struct Node {
      int val;
      Node *left;
      Node *right;
      Node *next;
    }
    

    填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。

    初始状态下,所有 next 指针都被设置为 NULL。

    示例说明请见LeetCode官网。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node-ii/
    著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    解法一:层序遍历

    求解过程和 LeetCode-116-填充每个节点的下一个右侧节点指针 这道题完全一样,现在想想,116题中提到完美二叉树,应该使用完美二叉树的一些性质有更优的解法,而当前的解法是通用的二叉树的解法。

    • 首先,如果root为空或者左右子节点都为空,则不需要处理next指针,直接返回root。
    • 否则,当二叉树不只有一个节点时,利用队列对二叉树进行层序遍历记录二叉树每一层的节点,然后按顺序处理当前层每一个节点的next指针。由于处理过程中所有的节点顺序并没有进行改变,所以最后返回root。
    import com.kaesar.leetcode.Node;
    
    import java.util.LinkedList;
    import java.util.Queue;
    
    public class LeetCode_117 {
        /**
         * 处理方式同 LeetCode-116-填充每个节点的下一个右侧节点指针
         * @param root
         * @return
         */
        public static Node connect(Node root) {
            // 如果root为空或者左右节点都为空,不需要处理,直接返回root
            if (root == null) {
                return root;
            }
            if (root.left == null && root.right == null) {
                return root;
            }
            // 利用队列记录每层的节点
            Queue<Node> nodes = new LinkedList<>();
            nodes.add(root);
            while (!nodes.isEmpty()) {
                int count = nodes.size();
                Node last = nodes.poll();
                if (last.left != null) {
                    nodes.add(last.left);
                }
                if (last.right != null) {
                    nodes.add(last.right);
                }
    
                count--;
    //             处理每层的节点的next指针
                while (count > 0) {
                    Node curNode = nodes.poll();
                    if (curNode.left != null) {
                        nodes.add(curNode.left);
                    }
                    if (curNode.right != null) {
                        nodes.add(curNode.right);
                    }
                    last.next = curNode;
                    last = curNode;
                    count--;
                }
    
            }
            return root;
        }
    
        public static void main(String[] args) {
            Node root = new Node(1);
            root.left = new Node(2);
            root.right = new Node(3);
    
            root.print();
            connect(root);
            System.out.println();
            root.print();
        }
    }
    

    【每日寄语】 逃避压力是没有用的,只会让压力更嚣张,勇敢地去面对。

  • 相关阅读:
    【初学EXT】布局练习
    创建型模式总结(补充UML类图)
    数据库基本概念总结
    Word2010操作技巧总结
    VMWare虚拟机磁盘压缩和上网总结
    第一次用word2010发布文章到博客园记
    设计模式学习总结一原则及创建型模式
    为什么要开始写blog?
    Delphi异常处理总结
    设计模式总结之行为型模式
  • 原文地址:https://www.cnblogs.com/kaesar/p/15587261.html
Copyright © 2011-2022 走看看