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

     

  • 相关阅读:
    linux 下查看文件个数及大小
    weblogic日志小结
    Excel数据通过plsql导入到Oracle
    Linux查看外网IP
    linux挂载/卸载优盘
    git版本回退
    linux修改文件所属用户、用户组
    retry.RetryInvocationHandler (RetryInvocationHandler.java:invoke(140))
    Hadoop切换namenode为active
    Netty使用LineBasedFrameDecoder解决TCP粘包/拆包
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3426686.html
Copyright © 2020-2023  润新知