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();
                }
            }    
        }
    }
  • 相关阅读:
    java过滤器 Fliter
    input标签name、value与id属性
    python 简单的数据库操作之转账
    正则表达式基本语法
    适合新手的Python爬虫小程序
    如何使用EditPlus将json格式字符串默认为UTF-8格式
    codeforces 527C:STL set
    codeforces 527B:瞎搞
    HDU 3397 线段树
    HDU 3436:splay tree
  • 原文地址:https://www.cnblogs.com/23lalala/p/3506849.html
Copyright © 2011-2022 走看看