首页 > 学院 > 开发设计 > 正文

116. Populating Next Right Pointers in Each Node

2019-11-09 21:05:33
字体:
来源:转载
供稿:网友

就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(); } } }};
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表