题目连接:Leetcode 144 Binary Tree Preorder Traversal
解题思路:用栈模拟递归,每次向栈中放入当前结点的值,并将指针赋值为当前结点的左指针。如果当前指正为NULL,则取出栈顶元素,将指针赋值为它的右指针。
/**
* Definition for a binary tree node.
* 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> ans;
stack<TreeNode*> sta;
while (root != NULL) {
ans.push_back(root->val);
sta.push(root);
root = root->left;
while (!sta.empty() && root == NULL) {
root = sta.top()->right;
sta.pop();
}
}
return ans;
}
};