Given a binary tree, return the inorder traversal of its nodes' values.
Example:
Input: [1,null,2,3] 1 \ 2 / 3 Output: [1,3,2]
给定一个二叉树,计算其中序遍历结果。
二叉树的遍历一般分为两种,递归遍历和非递归遍历,递归遍历代码简洁,容易理解。非递归遍历实现时需借助辅助栈来实现,有些公司面试时指定用非递归的方式来实现。本文对二叉树中序遍历的两种方法进行记录:
递归版本:
/**
* 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> ret;
inorder(ret, root);
return ret;
}
void inorder(vector<int> &ret, TreeNode* root)
{
if(root == NULL)
return;
inorder(ret, root->left);
ret.push_back(root->val);
inorder(ret, root->right);
}
};
非递归版本:
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> ret;
stack<TreeNode*> st;
TreeNode* p = root;
while(p != nullptr || !st.empty())
{
if(p)
{
st.push(p);
p = p->left;
}
else
{
p = st.top();
st.pop();
ret.push_back(p->val);
p = p->right;
}
}
return ret;
}
};