Given a binary tree, return the preorder traversal of its nodes' values.
For example: Given binary tree{1,#,2,3},
1 2 / 3
return[1,2,3].
Note: Recursive solution is trivial, could you do it iteratively?
C++
/** * Definition for binary tree * 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 {}; vector<int> res; stack<TreeNode*> s{{root}}; while(!s.empty()){ TreeNode *t = s.top(); s.pop(); if (t->right) s.push(t->right); if (t->left) s.push(t->left); res.insert(res.end(),t->val); //res.insert(t->val); } return res; } };
转载于:https://www.cnblogs.com/vercont/p/10210289.html