二叉树的前序遍历(非递归)

版权声明:本文为自学而写,如有错误还望指出,谢谢^-^ https://blog.csdn.net/weixin_43871369/article/details/89554921

题目描述

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?

Solution 1(非递归)

/**
 * Definition for binary tree
 * 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>res;
        if(root==nullptr) return res;
        stack<TreeNode*>q;
        q.push(root);
        while(!q.empty())
        {
            TreeNode *front=q.top();
            q.pop();
            res.push_back(front->val);
            if(front->right!=nullptr)
                q.push(front->right);
            if(front->left!=nullptr)
                q.push(front->left);
        }
        return res;
    }
};

Solution 2(递归写法) 

/**
 * Definition for binary tree
 * 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>res;
        if(root==nullptr) return res;
        preOrder(root,res);
        return res;
    }
private:
    void preOrder(TreeNode *ptr,vector<int>&v)
    {
        if(ptr!=nullptr)
        {
            v.push_back(ptr->val);
            preOrder(ptr->left,v);
            preOrder(ptr->right,v);
        }
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_43871369/article/details/89554921
今日推荐