leetcode 144. 二叉树的前序遍历

问题描述

给定一个二叉树,返回它的 前序 遍历。

 示例:

输入: [1,null,2,3]  
   1
    \
     2
    /
   3 

输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?

代码(递归)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> ans;
        if(!root)return ans;
        preorder(root,ans);
        return ans;
    }
    void preorder(TreeNode* root,vector<int> &a)
    {
        if(root)a.push_back(root->val);
        if(root->left)preorder(root->left,a);
        if(root->right)preorder(root->right,a);
    }
};

结果:

执行用时 :8 ms, 在所有 C++ 提交中击败了17.48%的用户
内存消耗 :11.1 MB, 在所有 C++ 提交中击败了6.57%的用户

代码(迭代)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> ans;
        if(!root)return ans;
        TreeNode *tmp = root,*tmp2;
        stack<TreeNode*> st;
        st.push(tmp);
        while(!st.empty())
        {
            tmp2 = st.top();
            ans.push_back(tmp2->val);   
            st.pop();    
            if(tmp2->right)st.push(tmp2->right);   
            if(tmp2->left)st.push(tmp2->left);
            
        }
        return ans;
    }
};

结果:

执行用时 :4 ms, 在所有 C++ 提交中击败了72.14%的用户
内存消耗 :10.8 MB, 在所有 C++ 提交中击败了8.86%的用户

代码(迭代2)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> ans;
        if(!root)return ans;
        TreeNode *tmp = root,*tmp2;
        stack<TreeNode*> st;
        while(tmp || !st.empty())
        {
            if(tmp)
            {
                st.push(tmp);
                ans.push_back(tmp->val);
                tmp = tmp->left;
            }
            else{
                tmp2 = st.top();
                st.pop();
                tmp = tmp2->right;
            }
        }
        return ans;
    }
};

结果:

执行用时 :4 ms, 在所有 C++ 提交中击败了72.36%的用户
内存消耗 :10.9 MB, 在所有 C++ 提交中击败了8.37%的用户
posted @ 2020-03-07 10:29  曲径通霄  阅读(132)  评论(0编辑  收藏  举报