1.题目
Given a binary tree, return the inorder traversal of its nodes’ values.
For example:
Given binary tree [1,null,2,3],
1
\
2
/
3
return [1,3,2].
Note: Recursive solution is trivial, could you do it iteratively?
2.题意
二叉树中序遍历
3.分析
思路类似于Binary Tree Preorder Traversal
非递归解法借助栈,先将左孩子节点进栈,当左孩子节点为空,再将当前栈顶元素出栈,遍历其右子树
4.代码
1)递归版
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
inorder(result, root);
return result;
}
private:
void inorder(vector<int> &result, TreeNode *root) {
if(root == nullptr)
return;
inorder(result, root->left);
result.push_back(root->val);
inorder(result, root->right);
}
};
2)迭代版
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
if(root == nullptr)
return result;
stack<const TreeNode*> s;
const TreeNode *p = root;
while(p != nullptr || !s.empty())
{
if(p != nullptr)
{
s.push(p);
p = p->left;
}
else
{
p = s.top();
s.pop();
result.push_back(p->val);
p = p->right;
}
}
return result;
}
};