Populating Next Right Pointers in Each Node

题目名称
Populating Next Right Pointers in Each Node—LeetCode链接

描述
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

分析
  第一想到的就是递归,代码很简单。

C++代码

/**
 * Definition for binary tree with next pointer.
 * struct TreeLinkNode {
 *  int val;
 *  TreeLinkNode *left, *right, *next;
 *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 * };
 */
class Solution {
public:
    void connect(TreeLinkNode *root) {
        if(!root || !root->left)
            return;
        root->left->next = root->right;
        if(root->next)
            root->right->next=root->next->left;
        connect(root->left);
        connect(root->right); 
    }
};

总结
  一开始很难懂void类型的函数的返回值问题,最近在Essential C++中看到关于函数返回值的问题:
  如果函数的返回类型不为void,那么它必须在每个可能的退出点上将值返回。函数中的每条return语句都被用来明确表示该处就是函数的退出点。
  return语句的第二种形式不反悔任何数值。这种形式只在返回值为void时才会被使用。它用来提前结束函数的执行。

你可能感兴趣的:(LeetCode)