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

     

  • 相关阅读:
    public/private/protected的具体区别
    解决密码自动填充的问题
    tp导出excel
    好久没更了,确实太忙了--dedecms篇
    解决css的float父div没有高度
    随笔
    总结最近写的h5项目
    ajax删除当前行
    开发时常遇到的小问题
    js处理时间戳
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3426686.html
Copyright © 2011-2022 走看看