• Populating Next Right Pointers in Each Node


    Given a binary tree

        struct TreeLinkNode {
          TreeLinkNode *left;
          TreeLinkNode *right;
          TreeLinkNode *next;
        }
    

    Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set toNULL.

    Initially, all next pointers are set to NULL.

    Note:

    • You may only use constant extra space.
    • You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).

    For example,
    Given the following perfect binary tree,

             1
           /  
          2    3
         /   / 
        4  5  6  7
    

    After calling your function, the tree should look like:

             1 -> NULL
           /  
          2 -> 3 -> NULL
         /   / 
        4->5->6->7 -> NULL

    solution:
    这其实就是个BFS,使用一个队列既可,为了方便,在每一层扩展完之后向队列中加入一个null。在对next point 赋值时,如果发现下一项是null,则直接给next = null.

    由于只能使用constant 空间,所以不能这么做,由于是一棵树,所以考虑递归。
     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         // Start typing your Java solution below
    12         // DO NOT write main() function
    13         if(root == null) return;
    14         if(root.left != null){
    15             root.left.next = root.right;
    16         }
    17         if(root.right != null){
    18             root.right.next = ((root.next != null)? root.next.left : null);
    19         }
    20         connect(root.left);
    21         connect(root.right);
    22     }
    23 }
  • 相关阅读:
    CCNA 第二章 以太网回顾
    CCNA 第一章 网络互联
    solidworks中 toolbox调用出现未配置的解决方法
    linux之df命令
    linux之du命令
    linux之pid文件
    linux之mysql启动问题
    linux之使用cron,logrotate管理日志文件
    wordpress(一)wordpress环境的搭建
    phpwind8.7升级9.0.1过程(四)20130207升级到20141228
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3313824.html
Copyright © 2020-2023  润新知