[LeetCode 題解]: Binary Tree Preorder Traversal

前言

 

【LeetCode 題解】系列傳送門:  http://www.cnblogs.com/double-win/category/573499.htmlhtml

 

1.題目描述

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

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

   1
    \
     2
    /
   3

return [1,2,3].code

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

2. 題意

 

先序遍歷二叉樹,遞歸的思路是普通的,可否用迭代呢?blog

 

3. 思路

非遞歸思路:<藉助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;
    }

遞歸思路:get

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

4.相關題目

(1)二叉樹的中序遍歷:it

(2)二叉樹的後序遍歷:io

(3) 二叉樹系列文章:

做者:Double_Win

出處: http://www.cnblogs.com/double-win/p/3896010.html 

聲明: 因爲本人水平有限,文章在表述和代碼方面若有不妥之處,歡迎批評指正~

相關文章
相關標籤/搜索