zoukankan      html  css  js  c++  java
  • Populating Next Right Pointers in Each Node II

    Follow up for problem "Populating Next Right Pointers in Each Node".

    What if the given tree could be any binary tree? Would your previous solution still work?

    Note:

    • You may only use constant extra space.

    For example,
    Given the following binary tree,

             1
           /  
          2    3
         /     
        4   5    7
    

    After calling your function, the tree should look like:

             1 -> NULL
           /  
          2 -> 3 -> NULL
         /     
        4-> 5 -> 7 -> NULL

    /**
     * Definition for binary tree with next pointer.
     * public class TreeLinkNode {
     *     int val;
     *     TreeLinkNode left, right, next;
     *     TreeLinkNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public void connect(TreeLinkNode root) {
            if (root==null){
                return;
            }
            Queue<TreeLinkNode> queue1 = new LinkedList<TreeLinkNode>();
            Queue<TreeLinkNode> queue2 = new LinkedList<TreeLinkNode>();
            queue1.offer(root);
            TreeLinkNode pre = root;
            TreeLinkNode p = null;
            while (!queue1.isEmpty()||!queue2.isEmpty()){
                while (!queue1.isEmpty()) {
                    p = queue1.poll();
                    pre.next = p;
                    pre = p;
                    if (p.left!=null) {
                        queue2.offer(p.left);
                    }
                    if (p.right!=null) {
                        queue2.offer(p.right);
                    }
    
                }
                if (p!=null){
                    p.next = null;
                }
                if (!queue2.isEmpty()) {
                    pre = queue2.peek();
                }
                while (!queue2.isEmpty()) {
                    p = queue2.poll();
                    pre.next = p;
                    pre = p;
                    if (p.left!=null) {
                        queue1.offer(p.left);
                    }
                    if (p.right!=null) {
                        queue1.offer(p.right);
                    }
    
                }
                if (p!=null){
                    p.next = null;
                }
                if (!queue1.isEmpty()) {
                    pre = queue1.peek();
                }
            }    
        }
    }
  • 相关阅读:
    Kubernetes日常维护命令
    4-docker的三要素
    3-docker的安装
    2-docker介绍
    1-为什么要使用docker
    块存储、文件存储、对象存储意义及差异
    ceph分布式存储的搭建
    YAML入门:以创建一个Kubernetes deployment为例
    Zabbix通过SQL语句从数据库获取数据说明
    图解HTTP--03--http报文内的信息
  • 原文地址:https://www.cnblogs.com/23lalala/p/3506849.html
Copyright © 2011-2022 走看看