Problem
Given a binary tree, return the inorder traversal of its nodes’ values.
For example:
Given binary tree [1,null,2,3]
,
1 \ 2 / 3
return [1,3,2]
.
Note: Recursive solution is trivial, could you do it iteratively?
Solution: Recursion
Time complexity: O(n)
Space complexity: O(h)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
// Author: Huahua // Running time: 4 ms class Solution { public: vector<int> inorderTraversal(TreeNode* root) { vector<int> ans; inorderTraversal(root, ans); return ans; } private: void inorderTraversal(TreeNode* root, vector<int>& ans) { if (root == nullptr) return; inorderTraversal(root->left, ans); ans.push_back(root->val); inorderTraversal(root->right, ans); } }; |
Solution 2: Iterative
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// Author: Huahua // Running time: 3 ms lass Solution { public: vector<int> inorderTraversal(TreeNode* root) { if (root == nullptr) return {}; vector<int> ans; stack<TreeNode*> s; TreeNode* curr = root; while (curr != nullptr || !s.empty()) { while (curr != nullptr) { s.push(curr); curr = curr->left; } curr = s.top(); s.pop(); ans.push_back(curr->val); curr = curr->right; } return ans; } }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment