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: stack<TreeNode *> stk;
14: vector<int> res;
15: if (root == NULL) return res;
16: stk.push(root);
17: while (!stk.empty()) {
18: TreeNode *t = stk.top();
19: stk.pop();
20: res.push_back(t->val);
21: if (t->right) stk.push(t->right);
22: if (t->left) stk.push(t->left);
23: }
24: return res;
25: }
26: };
Saturday, August 13, 2016
144. Binary Tree Preorder Traversal
Not much to say. Pretty straightforward.
Labels:
leetcode,
preorder traversal,
tree
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment