前序遍历。用栈node_stack维护要访问的结点指针。
每次访问栈顶,输出结点的值,再将其右左儿子压入栈中 —— 注意到因为每次都是访问栈顶,所以要先压右儿子后压左儿子,来保证前序遍历。
代码:
class Solution
{
public:
vector<int> preorderTraversal(TreeNode *root)
{
vector<int> ret;
stack<TreeNode*> node_stack;
node_stack.push(root);
while (node_stack.empty()==false)
{
TreeNode* top = node_stack.top();
node_stack.pop();
if (top == NULL)
{
continue;
}
ret.push_back(top->val);
node_stack.push(top->right);
node_stack.push(top->left);
}
return ret;
}
};