1,题目要求
Given a binary tree, return the inorder traversal of its nodes’ values.
对于一颗二叉树,给出中序遍历的结果。
2,题目思路
对于这道题,如果是仅仅使用递归的方法是非常简单的,也是中序遍历的常规实现办法。
而如果是迭代的方法去做的话,情况就会有差别了。
一般对于树的问题,如果要用非递归的方法实现,一般需要使用到的容器为栈或队列。比如,对于树的层次遍历而言,实现起来使用的就是队列。而对于这道题,所用到的就栈了。
实现原理为,利用栈首先去记录所有可遍历到的左孩子节点,然后在当前左孩子全部遍历完成后,取栈顶的值并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;
}
};