LeetCode 144. Binary Tree Preorder Traversal 题解(C++)
题目描述
- Given a binary tree, return the preorder traversal of its nodes’ values.
举例
- Given binary tree {1,#,2,3},
return [1,2,3].
补充
- Recursive solution is trivial, could you do it iteratively?
思路
递归
- 参照之前的中序遍历,只需把输出的代码(即放入数组中)放在前面即可。可参考:树的中序遍历
非递归
- 非递归算法使用栈实现。首先先把根结点入栈,之后若栈不为空,则不断循环,每次先输出栈顶结点,之后检测栈顶结点的右结点是否为空,不为空则进栈,再检测栈顶结点的左结点,不为空则进栈,直至栈空。
代码
递归
class Solution
{
public:
vector<int> preorderTraversal(TreeNode* root)
{
vector<int> res;
preTraversal(root, res);
return res;
}
void preTraversal(TreeNode *root, vector<int> &res)
{
if (root == NULL)
{
return;
}
res.push_back(root->val);
preTraversal(root->left, res);
preTraversal(root->right, res);
}
};
非递归
class Solution
{
public:
vector<int> preorderTraversal(TreeNode* root)
{
vector<int> res;
stack<TreeNode*> sta;
if (root == NULL)
{
return res;
}
sta.push(root);
while (!sta.empty())
{
TreeNode *temp = sta.top();
sta.pop();
res.push_back(temp->val);
if (temp->right != NULL)
{
sta.push(temp->right);
}
if (temp->left != NULL)
{
sta.push(temp->left);
}
}
return res;
}
};