编程问题:
给定一个二叉树的根节点 root ,返回它的 中序 遍历。
问题描述:
- 输入:root = [1,null,2,3]
输出:[1,3,2] - 输入:root = []
输出:[] - 输入:root = [1]
输出:[1]
解法:
1.递归
时间复杂度O(N)
空间复杂度O(N)
/**
* 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> res;
void dfs(TreeNode *root)
{
if (root)
{
dfs(root->left);
res.push_back(root->val);
dfs(root->right);
}
}
vector<int> inorderTraversal(TreeNode* root) {
dfs(root);
return res;
}
};
2.迭代
其实递归隐式地维护了一个栈,用迭代的方法只是显式地利用栈来实现。
时间复杂度O(N)
空间复杂度O(N)
/**
* 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> res;
stack<TreeNode *> s;
while (root || !s.empty())
{
while (root)
{
s.push(root);
root = root->left;
}
root = s.top();
res.push_back(root->val);
s.pop();
root = root->right;
}
return res;
}
};