/**
* 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) {
vector<int> ans;
stack<TreeNode *>s;
TreeNode *current;
if (root == NULL)
{
return ans;
}
s.push(root);
while (!s.empty())
{
current = s.top();
s.pop();
ans.push_back(current->val);
if (current->right != NULL)
s.push(current->right);
if (current->left !=NULL)
s.push(current->left);
}
return ans;
}
};
二叉树遍历144. Binary Tree Preorder Traversal
最新推荐文章于 2022-11-29 02:00:43 发布