[LeetCode] Binary Tree Inorder Traversal

94. Binary Tree Inorder Traversal

Given the root of a binary tree, return the inorder traversal of its nodes’ values.

Follow up: Recursive solution is trivial, could you do it iteratively?

  • Time : O(n)
  • Space : O(n)
    • also recursive solution use O(n) actual. (call stack)
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
vector<TreeNode*> st;
void push(TreeNode* node) {
while(node) {
st.push_back(node);
node = node->left;
}
}
public:
vector<int> inorderTraversal(TreeNode* root) {
if(!root) return {};
vector<int> res;
push(root);
while(!st.empty()) {
auto pop = st.back(); st.pop_back();
res.push_back(pop->val);
if(pop->right)
push(pop->right);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/09/PS/LeetCode/binary-tree-inorder-traversal/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.