-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0199-binary-tree-right-side-view.c
57 lines (46 loc) · 1.56 KB
/
0199-binary-tree-right-side-view.c
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
51
52
53
54
55
56
57
/*
Given a binary tree, return the right side view of it (the nodes which can
be seen in front when looking from the right).
Ex. 1 <-
/ \
2 3 <- -> [1, 3, 4]
\ \
5 4 <-
The right side view is basically the last element at each level of the tree.
So BFS is one way this problem can be solved.
The solution below uses recursion, where on reaching a new depth we add that
node as the right view for that depth. We recursively visit the right child
before the left child to get the right view.
Time: O(n)
Space: O(n)
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
void dfs(struct TreeNode* root, int* result, int* returnSize, int depth) {
if (root == NULL)
return;
// If a new depth is reached, add the node as right view for that depth
if (*returnSize <= depth) {
*returnSize += 1;
result[depth] = root->val;
}
// Visit the right child first then left child
dfs(root->right, result, returnSize, depth+1);
dfs(root->left, result, returnSize, depth+1);
}
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* rightSideView(struct TreeNode* root, int* returnSize) {
// Size of result array depends on the depth of tree, which can be precomputed
int* result = (int*) malloc(sizeof(int)*100);
*returnSize = 0;
dfs(root, result, returnSize, 0);
return result;
}