-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbinaryTreeInorderTraversal.cpp
More file actions
75 lines (62 loc) · 1.6 KB
/
binaryTreeInorderTraversal.cpp
File metadata and controls
75 lines (62 loc) · 1.6 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// https://leetcode.com/problems/binary-tree-inorder-traversal/
//
// Status: Accepted
// Runtime: 0 ms
// Score: 100 %
//
#include <iostream>
#include <vector>
#include <gtest/gtest.h>
#include "args.h"
#include "leetcode.h"
#include "macros.h"
using namespace std;
class Solution
{
public:
vector<int> inorderTraversal(TreeNode *root)
{
// inorder traversal is Left-Root-Right
vector<int> answer;
// Don't do anything if root is null
if (root != nullptr)
{
// Handle the left root
if (root->left != nullptr)
{
vector<int> temp = inorderTraversal(root->left);
answer.insert(answer.end(), temp.begin(), temp.end());
}
// handle the Root
if (root != nullptr)
{
answer.push_back(root->val);
}
// handle Right
if (root->right != nullptr)
{
vector<int> temp = inorderTraversal(root->right);
answer.insert(answer.end(), temp.begin(), temp.end());
}
}
return answer;
}
};
TEST(BinaryTreeInorderTraversal, CorrectSample)
{
Solution solution;
vector<int> correct = {1, 3, 2};
TreeNode node1(1);
TreeNode node2(2);
TreeNode node3(3);
TreeNode *root = &node1;
node1.right = &node2;
node2.left = &node3;
ASSERT_EQ(solution.inorderTraversal(root), correct);
}
TEST(BinaryTreeInorderTraversal, Empty)
{
Solution solution;
vector<int> empty;
ASSERT_EQ(solution.inorderTraversal(nullptr), empty);
}