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



    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 solve(TreeLinkNode *root) {
    12         // deal with leaf nodes
    13         if (root->left == NULL || root->right == NULL) return;
    14         root->left->next = root->right;
    15         if (root->next != NULL) root->right->next = root->next->left;
    16         else root->right->next = NULL;
    17         // recursive solve left and right child of root
    18         solve(root->left);
    19         solve(root->right);
    20     }
    21     void connect(TreeLinkNode *root) {
    22         if (root == NULL) return ;
    23         root->next = NULL;
    24         solve(root);
    25     } 
    26 };

  • 相关阅读:
    特殊集合
    推箱子
    集合
    数组

    循环语句 练习题
    穷举与迭代
    循环语句
    练习题
    switch case
  • 原文地址:https://www.cnblogs.com/Stomach-ache/p/3779874.html
Copyright © 2011-2022 走看看