zoukankan      html  css  js  c++  java
  • leetcode-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

    思路:起初觉得是个很难的题,但是后来发现了Note里面的限制(给定二叉树是完全二叉树),所以简单好多,只需要逐层处理即可。

    Accepted Code:
     1 /**
     2  * Definition for binary tree with next pointer.
     3  * struct TreeLinkNode {
     4  *  int val;
     5  *  TreeLinkNode *left, *right, *next;
     6  *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     void connect(TreeLinkNode *root) {
    12         if(root==nullptr)
    13         return;
    14         TreeLinkNode* pre=root;
    15         TreeLinkNode* cur=nullptr;
    16         while(pre->left)
    17         {
    18             cur=pre;
    19             while(cur)
    20             {
    21                 cur->left->next=cur->right;
    22                 if(cur->next)
    23                 {
    24                     cur->right->next=cur->next->left;
    25                     cur=cur->next;
    26                 }else
    27                 break;
    28             }
    29             pre=pre->left;
    30         }
    31     }
    32 };
  • 相关阅读:
    【计算机网络】宽带、基带传输
    【操作系统】多道程序的理解
    【操作系统】操作系统的理解
    NLP学习常用的网页链接
    linux下常用FTP命令 1. 连接ftp服务器[转]
    shell运行java/Jar 脚本
    jsp验证码
    用javascript实现的验证码
    eclipse设置高亮显示的颜色
    oracle 导出
  • 原文地址:https://www.cnblogs.com/hongyang/p/6464194.html
Copyright © 2011-2022 走看看