Populating Next Right Pointers in Each Node

原题点这

给定一个完全二叉树,不同的是每个节点有个额外的next域,目的是通过这些next域将同层的所有节点串接起来。

问题结合着程序和给定的实例,自己走一遍就明白了,如果思路不是很清晰,建议自己要么把这个例子走一遍,要么自己画个更复杂的模拟程序走一遍,否则没效果。O(∩_∩)O~

Populating Next Right Pointers in Each Node_第1张图片

图画的有点像彩票开奖的节奏啊。。。

//code

/**
 * 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) {
        //NULL or has no children, nothing to do.
        if(root == NULL || root->left == NULL) 
          return;
        TreeLinkNode *left = root->left;
        TreeLinkNode *right = root->right;
        while(left != NULL)
        {
          left->next = right;
          left = left->right;
          right = right->left;
        }
        connect(root->left);
        connect(root->right);
    }
};



你可能感兴趣的:(LeetCode,Algorithm,递归,完全二叉树)