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]
.
此题之前和文清讨论过,一次过了。但是总体难度上,比后续迭代简单不少。
/** * 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) { vector<int> re; if(root == NULL)return re; stack<TreeNode*> sk; sk.push(root); while(!sk.empty()) { TreeNode *now = sk.top(); sk.pop(); re.push_back(now->val); if(now->right != NULL) sk.push(now->right); if(now->left != NULL) sk.push(now->left); } return re; } };