1. 题目

Leetcode#144. 二叉树的前序遍历,C++实现

2. 方法一递归

2.1. 代码

class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        dfs(root);
        return temp;
    }
    
    void dfs(TreeNode* root){
        if(root==NULL) return;
        temp.push_back(root->val);
        dfs(root->left);
        dfs(root->right);
    }
    vector<int> temp;
};

2.2. 结果

Leetcode#144. 二叉树的前序遍历,C++实现

3. 方法二非递归

3.1. 代码

使用堆栈

class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> display;
        if(root==NULL) return display;
        stack<TreeNode*> temp;
        
        while(root!=NULL||!temp.empty()){
            if(root==NULL){
                root=temp.top();
                temp.pop();
                root=root->right;
            }else{
                display.push_back(root->val);
                temp.push(root);
                root=root->left;
            }
        }
        return display;
        
    }
};

3.2. 结果

Leetcode#144. 二叉树的前序遍历,C++实现

相关文章: