[Leetcode problem]: Binary Tree preorder traversal

Source: Internet
Author: User

Given a binary tree, returnPreorderTraversal of its nodes 'values.

For example:
Given Binary Tree{1,#,2,3},

   1         2    /   3

 

Return[1,2,3].

Note:Recursive solution is trivial, cocould You Do It iteratively?

Question

The binary tree is first traversed sequentially. The recursive idea is common. Can we use iteration?

Non-recursive approach: <using Stack>

    vector<int> preorderTraversal(TreeNode *root) {        stack<TreeNode* > st;        vector<int> vi;        vi.clear();        if(!root) return vi;                st.push(root);        while(!st.empty()){            TreeNode *tmp = st.top();            vi.push_back(tmp->val);                st.pop();            if(tmp->right) st.push(tmp->right);            if(tmp->left) st.push(tmp->left);        }        return vi;    }

Recursive thinking:

class Solution {private:    vector<int> vi;public:    vector<int> preorderTraversal(TreeNode *root) {        vi.clear();        if(!root) return vi;        preorder(root);return vi;    }    void preorder(TreeNode* root){        if(!root) return;        vi.push_back(root->val);        preorder(root->left);        preorder(root->right);    }};

-------------------------------------------------

Double_win

Source: http://www.cnblogs.com/double-win/p/3895822.html

Disclaimer: Due to my limited level, if there is anything wrong with the expression and code in the article, please criticize and correct it ~

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.