'lintcode 二叉树的前序遍历' Posted on 2019-04-12 | In algorithm lincode 二叉树的前序遍历描述给出一棵二叉树,返回其节点值的前序遍历。 样例给出一棵二叉树 {1,#,2,3}, 返回 [1,2,3]. 思路堆栈实现,先压入右儿子,再压入左儿子 代码12345678910111213141516171819202122232425262728293031323334353637/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */class Solution {public: /** * @param root: A Tree * @return: Preorder in ArrayList which contains node values. */ vector<int> preorderTraversal(TreeNode * root) { // write your code here vector<int> res; if (!root) return res; stack<TreeNode *> s; s.push(root); while(!s.empty()){ TreeNode *temp = s.top(); s.pop(); res.push_back(temp->val); if (temp->right) s.push(temp->right); if (temp->left) s.push(temp->left); } return res; }}; -------------end of filethanks for reading-------------