力扣 144. 二叉樹的前序遍歷 遞歸/非遞歸

https://leetcode-cn.com/problems/binary-tree-preorder-traversal/
在這裏插入圖片描述

思路一:根左右,遞歸版隨便寫。

/**
 * 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;
    }
};

思路二:非遞歸版,搞一個棧stkstk,因爲棧是後進先出的,所以每次先把棧頂節點的右兒子壓進去,再把左兒子壓進去即可。

/**
 * 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;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章