题目链接:https://leetcode-cn.com/problems/binary-tree-preorder-traversal/
给定一个二叉树,返回它的 前序 遍历。
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 vector<int> preorderTraversal(TreeNode* root) { 13 vector<int> result; 14 const TreeNode *p; 15 stack<const TreeNode *> s; 16 p=root; 17 if(p!=nullptr) s.push(p); 18 while(!s.empty()){ 19 p=s.top(); 20 s.pop(); 21 result.push_back(p->val); 22 if(p->right!=nullptr) s.push(p->right); 23 if(p->left!=nullptr) s.push(p->left); 24 } 25 return result; 26 } 27 };