首页 > 代码库 > Leetcode Binary Tree Preorder Traversal

Leetcode Binary Tree Preorder Traversal

Given a binary tree, return the preorder traversal of its nodes‘ values.

For example:
Given binary tree {1,#,2,3},

   1         2    /   3

 

return [1,2,3].

Note: Recursive solution is trivial, could you do it iteratively?

本题是非递归先序遍历二叉树,任何一本数据结构书上都有

vector<int> preorderTraversal(TreeNode * root){    vector<int> res;    if(root == NULL) return res;    stack<TreeNode *> record;    record.push(root);    while(!record.empty()){        TreeNode *node = record.top();        record.pop();        res.push_back(node->val);        if(node->right) record.push(node->right);        if(node->left) record.push(node->left);    }        return res;}