给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,3,2]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
解题思路:
这是最简单的中序遍历题目,如果用递归即dfs的方法,几步就可以完成,思路很容易理解,代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> ans;
if(!root){
return ans;
}
dfs(ans, root);
return ans;
}
void dfs(vector<int>& ans, TreeNode* root){
if(root->left){
dfs(ans, root->left);
}
ans.push_back(root->val);
if(root->right){
dfs(ans, root->right);
}
}
};
当然也可以用迭代的算法,这里使用的数据结构是栈的方式,思路是不停地把左子节点放入栈中,直到没有,这时候出栈,然后再往右子节点走,代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> ans;
stack<TreeNode*> st;
TreeNode* cur = root;
while(!st.empty() || cur != NULL){
//指针不为空或栈不为空
if(cur != NULL){
st.push(cur);
cur = cur->left;
}else{
cur = st.top();
st.pop();
ans.push_back(cur->val);
cur = cur->right;
}
}
return ans;
}
};