• LeetCode OJ 116. 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 to NULL.

    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
    

    对于这个题目我们可以很方便的采用层序遍历来解决,每次遍历一层把下一层的节点依次连接起来。由于每一层相当于形成了一个链表,树的最左边的节点就是每一层的起始节点。我们遍历这个链表,把链表中每一个节点的左右节点相连,然后把链表中相邻节点的左孩子和右孩子相连即可。

    代码如下:

     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         if(root==null) return;
    12         TreeLinkNode temp = root;
    13         if(temp.left!=null){
    14             while(temp!=null){    //遍历一层
    15                 temp.left.next = temp.right;
    16                 if(temp.next!=null){
    17                     temp.right.next = temp.next.left;
    18                 }
    19                 else{
    20                     temp.right.next = null;
    21                 }
    22                 temp = temp.next;
    23             }
    24             connect(root.left);    //遍历下一层
    25         }
    26         return;
    27     }
    28 }
  • 相关阅读:
    01-HTML控件
    08-多线程
    07-Log日志
    06-File-文件
    05-函数式编程
    04-异常使用处理
    03-常用包模块
    02-包
    Java NIO(六) Selector
    Java NIO(四) Scatter/Gather
  • 原文地址:https://www.cnblogs.com/liujinhong/p/5459290.html
Copyright © 2020-2023  润新知