zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    java基础 01
    c++11——模板的细节改进
    c++11——auto,decltype类型推导
    poj_1182 并查集
    poj_1988 并查集
    poj_1161 并查集
    poj_3067 树状数组
    poj_2182 线段树/树状数组
    poj_1190 树状数组
    动态规划
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3313824.html
Copyright © 2011-2022 走看看