就bfs就行啦,一次ac
/** * 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) { queue<TreeLinkNode*>qu; if(root == NULL) return ; qu.push(root); int num = 1; while(!qu.empty()){ TreeLinkNode* t; TreeLinkNode* PRe; int n = num; num = 0; for(int i = 1; i <= n; ++ i){ t = qu.front(); qu.pop(); if(t -> left != NULL){ num++; qu.push(t -> left); } if(t -> right != NULL){ num++; qu.push(t -> right); } if(i == n) t -> next = NULL; else t -> next = qu.front(); } } }};新闻热点
疑难解答