LeetCode 94. Binary Tree Inorder Traversal 题解(C++)
题目描述
- Given a binary tree, return the inorder traversal of its nodes’ values.
举例
- Given binary tree [1,null,2,3],
return [1,3,2].
补充
- Recursive solution is trivial, could you do it iteratively?
思路
递归解法
- 先对左子树做递归遍历,然后输出根节点,再对右子树进行递归遍历,递归出口为结点为空。
非递归解法
- 非递归解法使用栈实现,首先从根节点开始把左结点不断入栈,直到该结点无左节点,就把该结点出栈保存到结果数组,并使当前结点指向该结点的右节点,不断重复上述的步骤直到栈空且当前结点为空。
代码
递归代码
class Solution
{
public:
vector<int> inorderTraversal(TreeNode* root)
{
vector<int> res;
traversal(root, res);
return res;
}
void traversal(TreeNode* root, vector<int> &res)
{
if (root == NULL)
{
return;
}
traversal(root->left, res);
res.push_back(root->val);
traversal(root->right, res);
}
};
非递归代码
class Solution
{
public:
vector<int> inorderTraversal(TreeNode* root)
{
vector<int> res;
if (root == NULL)
{
return res;
}
stack<TreeNode*> sta;
TreeNode *p = root;
while (!sta.empty() || p)
{
if (p)
{
sta.push(p);
p = p->left;
}
else
{
p = sta.top();
sta.pop();
res.push_back(p->val);
p = p->right;
}
}
return res;
}
};