-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPopulatingNextRightPointersinEachNode.cpp
More file actions
executable file
·50 lines (45 loc) · 1.31 KB
/
PopulatingNextRightPointersinEachNode.cpp
File metadata and controls
executable file
·50 lines (45 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//
// PopulatingNextRightPointersinEachNode.cpp
// leetcode
//
// Created by witwolf on 5/4/15.
// Copyright (c) 2015 witwolf. All rights reserved.
//
#include <deque>
#include <utility>
using namespace std;
/**
* 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;
}
deque<pair<TreeLinkNode*,int>> nodes(1,make_pair(root, 1));
while(!nodes.empty()){
pair<TreeLinkNode*,int> p = nodes.front();
nodes.pop_front();
TreeLinkNode* node = p.first;
int level = p.second + 1;
if(node->left){
if(!nodes.empty() && nodes.back().second == level){
nodes.back().first->next = node->left;
}
nodes.push_back(make_pair(node->left, level));
}
if(node->right){
if(!nodes.empty() && nodes.back().second == level){
nodes.back().first->next = node->right;
}
nodes.push_back(make_pair(node->right, level));
}
}
}
};