Binary Tree Preorder Traversal
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?
思路:
深度优先搜索用栈进行。
题解:
/** * 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 == nullptr) return vector<int>(); vector<int> values; stack<TreeNode*> visits; visits.push(root); while(!visits.empty()) { auto node = visits.top(); visits.pop(); values.push_back(node->val); if (node->right) visits.push(node->right); if (node->left) visits.push(node->left); } return values; } };