-
Notifications
You must be signed in to change notification settings - Fork 1
/
BinaryTreeInorderTraversal.cpp
45 lines (43 loc) · 1.17 KB
/
BinaryTreeInorderTraversal.cpp
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
/*
Given a binary tree, return the inorder traversal of its nodes' values.
Note: Recursive solution is trivial, could you do it iteratively?
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode *root) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
vector<int> result;
Inorder(root,result);
return result;
}
void Inorder(TreeNode *root,vector<int> &result)
{
if(!root)
return;
Inorder(root->left,result);
result.push_back(root->val);
Inorder(root->right,result);
}
// iterative method
vector<int> inorderTraversal_2(TreeNode *root) {
vector<int> res;
stack<TreeNode *> stk;
TreeNode *cur = root;
while (cur || !stk.empty())
{
if (cur)
{
stk.push(cur);
cur = cur->left;
}
else if (!stk.empty())
{
res.push_back(stk.top()->val);
cur = stk.top()->right;
stk.pop();
}
}
return res;
}
};