力扣 144. 二叉树的前序遍历 递归/非递归

https://leetcode-cn.com/problems/binary-tree-preorder-traversal/
力扣 144. 二叉树的前序遍历 递归/非递归_第1张图片

思路一:根左右,递归版随便写。

/**
 * 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> ans;
    void preorder(TreeNode *root){
     
        ans.push_back(root->val);
        if(root->left)
            preorder(root->left);
        if(root->right)
            preorder(root->right);
    }
    vector<int> preorderTraversal(TreeNode* root) {
     
        if(root==NULL)
            return ans;
        preorder(root);
        return ans;
    }
};

思路二:非递归版,搞一个栈 s t k stk stk,因为栈是后进先出的,所以每次先把栈顶节点的右儿子压进去,再把左儿子压进去即可。

/**
 * 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> ans;
    vector<int> preorderTraversal(TreeNode* root) {
     
        if(root==NULL)
            return ans;
        stack<TreeNode*> stk;
        stk.push(root);
        TreeNode *cur;
        while(!stk.empty()){
     
            cur=stk.top();
            stk.pop();
            ans.push_back(cur->val);
            if(cur->right)
                stk.push(cur->right);
            if(cur->left)
                stk.push(cur->left);
        }
        return ans;
    }
};

你可能感兴趣的:(栈,力扣,DFS)