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();
                }
            }    
        }
    }
  • 相关阅读:
    基于注解的IOC配置
    字符串典型问题分析
    指针与数组
    数组的本质
    数组与指针分析
    指针的本质
    #与##操作符使用
    #pragma使用分析
    #error和#line使用分析
    条件编译使用
  • 原文地址:https://www.cnblogs.com/23lalala/p/3506849.html
Copyright © 2011-2022 走看看