leet code
929 - Binary Tree Inorder Traversal
성능이 많이 안 좋게 나왔는데, recursive 방식으로 시도했기 때문인 것 같습니다.
while로 한 번 더 풀어보면 좋겠습니다.
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 | /**
* 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 {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> rslt;
return it(root, rslt);
}
private:
vector<int> it(TreeNode* root, vector<int>& rslt)
{
if(root==nullptr) return rslt;
// check left
if(root->left)
{
it(root->left, rslt);
}
// check root
rslt.push_back(root->val);
// check right
if(root->right)
{
it(root->right, rslt);
}
return rslt;
}
};
|