LeetCode Binary Tree Preorder Traversal
/** * 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> res; if (root == NULL) return res; vector<TreeNode*> stack; stack.push_back(root); while(!stack.empty()){ TreeNode* n = stack.back(); stack.pop_back(); res.push_back(n->val); if (n->right != NULL) stack.push_back(n->right); if (n->left != NULL) stack.push_back(n->left); } } };
水一发,非递归通用实现见 LeetCode Binary Tree Inorder Traversal