Problem
Given the root of a binary tree, return the preorder traversal of its nodes’ values.
Example1
Input: root = [1,null,2,3]
Output: [1,2,3]
Example2
Input: root = []
Output: []
Example3
Input: root = [1]
Output: [1]
Example4
Input: root = [1,2]
Output: [1,2]
Example5
Input: root = [1,null,2]
Output: [1,2]
Solution
/**
* 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> preorderTraversal(TreeNode* root) {
if(!root)
return {};
stack<TreeNode *> stk;
vector<int> ret;
TreeNode *cur = root;
while(cur || !stk.empty())
{
while(cur)
{
ret.push_back(cur->val);
stk.push(cur);
cur = cur->left;
}
TreeNode *tmp = stk.top();
stk.pop();
cur = tmp->right;
}
return ret;
}
};