94. Binary Tree Inorder Traversal
Problem:
Given a binary tree, return the inorder traversal of its nodes' values.
Example:
Input: [1,null,2,3]
1
\
2
/
3
Output: [1,3,2]
Follow up: Recursive solution is trivial, could you do it iteratively?
思路1:
使用递归。
Solution I (C++):
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> traverse;
inorderTraversal(root, traverse);
return traverse;
}
private:
void inorderTraversal(TreeNode *root, vector<int> &traverse) {
if (!root) return;
inorderTraversal(root->left, traverse);
traverse.push_back(root->val);
inorderTraversal(root->right, traverse);
}
性能:
Runtime: 4 ms Memory Usage: 9.3 MB
思路2:
使用利用栈的迭代。
Solution II (C++):
vector<int> inorderTraversal(TreeNode* root) {
vector<int> traverse;
stack<TreeNode*> stk;
while (root || !stk.empty()) {
while (root) {
stk.push(root);
root = root->left;
}
root = stk.top();
stk.pop();
traverse.push_back(root->val);
root = root->right;
}
return traverse;
}
性能:
Runtime: 4 ms Memory Usage: 9.2 MB
相关链接如下:
知乎:littledy
GitHub主页:https://github.com/littledy
github.io:https://littledy.github.io/
欢迎关注个人微信公众号:小邓杂谈,扫描下方二维码即可
作者:littledy
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。