题目
给定一个二叉树,返回其中序遍历。
输入:root = [1,null,2,3]
输出:[1,3,2]
原题链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal/
思路
思路1
递归。
- 复杂度分析
- 时间复杂度 O(n)。遍历所有节点。
- 空间复杂度 O(n)。空间取决于递归层数,树的极端情况为 n 层。
思路2
用 stack 来模拟递归过程。先不断遍历左节点,直到没有为止。然后访问当前节点,再访问右节点。
- 复杂度分析
- 时间复杂度 O(n)。遍历所有节点。
- 空间复杂度 O(n)。空间取决于栈的大小,极端情况为 n。
思路3
Morris 法。将树转成链表。时间换空间。太绕了。暂时先不写了。
代码
代码1
/**
* 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> results;
travel(results, root);
return results;
}
void travel(vector<int>& results, TreeNode* root) {
if (root == NULL) {
return;
}
travel(results, root->left);
results.push_back(root->val);
travel(results, root->right);
}
};
代码2
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> results;
stack<TreeNode*> node_stack;
while (root || !node_stack.empty()) {
while (root) {
node_stack.push(root);
root = root->left;
}
root = node_stack.top();
node_stack.pop();
results.push_back(root->val);
root = root->right;
}
return results;
}
};