Leetcode Binary Tree Preorder Traversal

OpenSoucre發表於2014-06-18

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;
}

 

 

相關文章