二叉树先根遍历

来源:互联网 发布:万彩动画大师 知乎 编辑:程序博客网 时间:2024/06/06 01:13

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

For example:
given a binary tree (1,#,2,3);

class Solution {public:   vector<int> recursive(TreeNode* root, vector<int>& ivec){        if(!root) return ivec;        ivec.push_back(root->val);        recursive(root->left,ivec);        recursive(root->right,ivec);        return ivec;    }    vector<int> preorderTraversal(TreeNode *root) {        vector<int> ivec;        recursive(root,ivec);        return ivec;    }};

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

class Solution {public:    vector<int> preorderTraversal(TreeNode* root) {        vector<int>ivec;        if(!root){            return ivec;       }        stack<TreeNode*>tStack;        tStack.push(root);        TreeNode* current;        while(!tStack.empty()) {            current = tStack.top();                tStack.pop();            ivec.push_back(current->val);            if(current->right != NULL){                tStack.push(current->right);            }            if(current->left != NULL){                tStack.push(current->left);            }        }      return ivec;   }};
0 0
原创粉丝点击