首页 > 代码库 > Populating Next Right Pointers in Each Node

Populating Next Right Pointers in Each Node

问题:将二叉树的所有结点指向他的右边的一个结点
分析:对于每一个结点来说,其操作都是一样的,除了他的左儿子指向右儿子外,其左儿子的全部右后辈均指向其右儿子的全部左后辈

/** * 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==NULL) return ;        TreeLinkNode *left,*right;        left=root->left,right=root->right;        while(left && right)        {            left->next=right;            left=left->right;            right=right->left;        }        connect(root->left);        connect(root->right);    }};