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
    
     1 /**
     2  * Definition for binary tree with next pointer.
     3  * public class TreeLinkNode {
     4  *     int val;
     5  *     TreeLinkNode left, right, next;
     6  *     TreeLinkNode(int x) { val = x; }
     7  * }
     8  */
     9 public class Solution {
    10     public void connect(TreeLinkNode root) {
    11         // IMPORTANT: Please reset any member data you declared, as
    12         // the same Solution instance will be reused for each test case.
    13         ArrayList<TreeLinkNode> queue = new ArrayList<TreeLinkNode>();
    14         if(root == null) return;
    15         queue.add(root);
    16         TreeLinkNode nl = new TreeLinkNode(Integer.MIN_VALUE);
    17         queue.add(nl);
    18         while(queue.size() != 1){
    19             TreeLinkNode rn = queue.remove(0);
    20             if(rn.val == Integer.MIN_VALUE){
    21                 queue.add(nl);
    22             }
    23             else{
    24                 rn.next = queue.get(0);
    25                 if(queue.get(0).val == Integer.MIN_VALUE) rn.next = null;
    26                 if(rn.left != null) queue.add(rn.left);
    27                 if(rn.right != null) queue.add(rn.right);
    28             }
    29         }
    30     }
    31 }

    使用BFS做的。

     

  • 相关阅读:
    JQuery源码解析(九)
    JQuery源码分析(八)
    C#的扩展方法解析
    JQuery基础DOM操作
    Ajax中的eval函数的用法
    EF上下文管理
    Asp.Net请求管道中的19个事件
    JQuery源码分析(七)
    SoftReference、WeakReference、PhantomRefrence分析和比较
    php 计算gps坐标 距离
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3426686.html
Copyright © 2011-2022 走看看