题目
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,3,2].
中序遍历
代码:
迭代:
/**
* Definition for binary tree
* 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;
vector<TreeNode*> stack; //堆栈
while(!stack.empty()||root!=NULL)
{
if(root!=NULL) //探索左分支,保留路径
{
stack.push_back(root);
root=root->left;
}
else //无左分支时输出并探索右分支
{
root=stack.back();
stack.pop_back();
ans.push_back(root->val);
root=root->right;
}
}
return ans;
}
};
传统的递归:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
vector<int> ans;
public:
void innerInorderTra(TreeNode *root) //递归
{
if(root!=NULL)
{
innerInorderTra(root->left);
ans.push_back(root->val);
innerInorderTra(root->right);
}
}
vector<int> inorderTraversal(TreeNode *root) {
ans.clear();
innerInorderTra(root);
return ans;
}
};
本文详细介绍了二叉树中序遍历的两种实现方式:迭代和递归。通过实例演示了如何使用栈进行中序遍历,以及传统递归方法的实现过程。适合对数据结构和算法感兴趣的读者。
1187

被折叠的 条评论
为什么被折叠?



