1,题目要求
Given a binary tree, return the inorder traversal of its nodes’ values.
给定二叉树,返回其节点值的中序遍历结果。
请返回递归和迭代两种方式的遍历结果。
2,题目思路
对于这道题,如果仅仅使用递归的方法来实现是比较简单的,具体就是设置return的base case,然后将操作语句放在中间,就可以实现中序遍历了。
而如果我们想要利用迭代的策略来实现,就需要有所差别。
正如我们在进行树的层次遍历时,使用到了队列这种容器。
对于一般的树的遍历问题, 如果想要使用非递归的方式来实现,就需要用到队列或者栈来去实现。
对于中序遍历而言,我们使用栈来去实现。
具体步骤为,首先利用栈去记录所有可遍历到的左孩子节点,然后在当前左孩子全部遍历完成之后,取栈顶的值并进行pop,然后再去遍历当前节点的右孩子,遍历到右孩子后,再尝试找到该节点的所有左孩子节点。
于是,利用这种向左找到底然后回退的方法,实现树的中序遍历。
中序遍历:
左孩子-根-右孩子
3,代码实现
1,递归
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
inorder(root, res);
return res;
}
void inorder(TreeNode* node, vector<int>& res)
{
if(node == nullptr) return;
inorder(node->left, res);
res.push_back(node->val);
inorder(node->right,res);
}
};
2,迭代
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
stack<TreeNode*> s;
vector<int> res;
TreeNode* node = root;
while(node!=nullptr || !s.empty())
{
while(node!= nullptr) {
s.push(node);
node = node->left;
}
node = s.top();s.pop();
res.push_back(node->val);
node = node->right;
}
return res;
}
};