目录
一、题目描述
二、初次解答
1. 思路:二叉树的中序遍历。访问二叉树的左子树,再访问二叉树的根节点,最后访问二叉树的右叉树。
2. 代码:
void order(struct TreeNode* root, int* ret, int* p){ if(!root) return; order(root->left, ret, p); ret[(*p)++]=root->val; order(root->right, ret, p); } int* inorderTraversal(struct TreeNode* root, int* returnSize) { int* ret=(int*)malloc(sizeof(int)*100); *returnSize=0; order(root, ret, returnSize); return ret; }
3. 优点:实现简单,容易想到,且仅需遍历一遍,时间复杂度为O(n)。
4. 缺点:需要递归栈空间,空间复杂度为O(n)。
三、官方解法
1. 思路:迭代遍历二叉树,手动维护栈。每次迭代访问子节点前,将当前节点地址保存到栈内,访问完左节点后,再访问当前节点,最后访问右节点。
2. 代码:
int* inorderTraversal(struct TreeNode* root, int* returnSize) { int* ret=malloc(sizeof(int)*100); struct TreeNode** tmp=malloc(sizeof(struct TreeNode*)*100); int top=0; *returnSize=0; while(root || top>0){ while(root){ tmp[top++]=root; root=root->left; } root=tmp[--top]; ret[(*returnSize)++]=root->val; root=root->right; } return ret; }
3. 优点:符合不采用迭代的要求,且时间复杂度为O(n)。
4. 缺点:手动维护栈,空间复杂度依旧为O(n)。
四、C++写法
/**
* 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 {
private:
void inorder(TreeNode* root, vector<int> &v) {
if (!root)
return;
inorder(root->left, v);
v.push_back(root->val);
inorder(root->right, v);
}
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> v;
inorder(root, v);
return v;
}
};
五、总结
当遇到二叉树中序遍历时,使用递归实现最简单,也可以采用迭代手动维护栈空间来实现。