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做的。

     

  • 相关阅读:
    素数推断算法(高效率)
    Hibernate的fetch
    TRIZ系列-创新原理-22-变害为利原理
    Offer是否具有法律效力?
    浅谈C++多态性
    C语言scanf函数详解
    大话设计模式之原型模式
    Android源码文件夹结构
    简单的REST的框架实现
    android startActivityForResult的用法
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3426686.html
Copyright © 2011-2022 走看看