/** * 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> result; if(root == NULL){ return result; } TreeNode *p = root; std::stack<TreeNode *> mystack; while(p || !mystack.empty()){ if(p) { result.push_back(p->val); mystack.push(p); p = p->left; } else { p = mystack.top(); p = p->right; mystack.pop(); } } return result; } };
Leetcode Binary Tree Preorder Traversal
原文地址:http://blog.csdn.net/wyj7260/article/details/39779495