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 };
  • 相关阅读:
    小制作之放大镜
    水平居中&垂直居中
    图片引入&路径问题
    接触网页的第一天
    Java 线程 面试题
    JAVA 名言精句
    字符串工具类
    js动态生成checkbox表单并设置为单选
    idea快捷键汇总(使用率高)
    XML mapping 数据解析
  • 原文地址:https://www.cnblogs.com/hongyang/p/6464194.html
Copyright © 2011-2022 走看看