Every day a leetcode
题目来源:94. 二叉树的中序遍历
解法1:递归
代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
#define MAX_NODE_SZIE 100
void inOrder(struct TreeNode* root, int* ans,int* ansSize)
{
if(root == NULL) return;
inOrder(root->left,ans,ansSize);
ans[(*ansSize)++]=root->val;
inOrder(root->right,ans,ansSize);
}
int* inorderTraversal(struct TreeNode* root, int* returnSize){
*returnSize=0;
int *ans=malloc(MAX_NODE_SZIE*sizeof(int));
inOrder(root,ans,returnSize);
return ans;
}
结果:
解法2:非递归
模拟一个栈,非递归实现中序遍历。
代码:
/**
* 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> ans;
stack<TreeNode*> s;
while(root || !s.empty())
{
while(root)
{
s.push(root);
root=root->left;
}
root=s.top();
s.pop();
ans.push_back(root->val);
root=root->right;
}
return ans;
}
};
结果: