[leetcode刷题系列]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) {}
 * };
 */
 
const int MAXN = 30;
TreeLinkNode * parr[MAXN];
class Solution {
    void dfs(TreeLinkNode * root, int dep){
        if(parr[dep] != 0)
            parr[dep]->next = root;
        parr[dep] = root;
        if(root->left != 0)
            dfs(root->left, dep + 1);
        if(root->right != 0)
            dfs(root->right, dep + 1);
    }
public:
    void connect(TreeLinkNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if(root == 0)
            return ;
        memset(parr, 0x00, sizeof(parr));
        dfs(root, 0);
    }
};


你可能感兴趣的:([leetcode刷题系列]Populating Next Right Pointers in Each Node)