-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path094-binary-tree-inorder-traversal.cpp
More file actions
66 lines (61 loc) · 1.73 KB
/
Copy path094-binary-tree-inorder-traversal.cpp
File metadata and controls
66 lines (61 loc) · 1.73 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
// 94. Binary Tree Inorder Traversal
//
// Given a binary tree, return the inorder traversal of its nodes' values.
// For example:
// Given binary tree {1,#,2,3},
// 1
// \
// 2
// /
// 3
// return [1,3,2].
//
// Note: Recursive solution is trivial, could you do it iteratively?
//
//
// Tags: Tree, Hash Table, Stack
//
// https://leetcode.com/problems/binary-tree-inorder-traversal/
#include <iostream>
#include <gtest/gtest.h>
#include <tree/tree.h>
#include <stack>
#include <vector>
using namespace std;
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode *>s;
if(root == NULL) return result;
TreeNode *node = root;
while(node != NULL || !s.empty()){
if(node){
s.push(node);
node = node->left;
}else{
node = s.top();
s.pop();
result.push_back(node->val);
node = node->right;
}
}
return result;
}
};
TEST(leetcode_094_binary_tree_inorder_traversal, Basic)
{
Solution *solution = new Solution();
vector<int> expected = {1, 3, 2};
EXPECT_EQ(expected, solution->inorderTraversal(tree_init({"1", "#", "2", "3"})));
expected = {2, 1};
EXPECT_EQ(expected, solution->inorderTraversal(tree_init({"1", "2"})));
expected = {2, 1, 3};
EXPECT_EQ(expected, solution->inorderTraversal(tree_init({"1", "2", "3"})));
expected = {2, 1, 6, 4, 3, 5};
EXPECT_EQ(expected, solution->inorderTraversal(tree_init({"1", "2", "3", "#", "#", "4", "5", "6"})));
}
int main(int argc, char *argv[]) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}