力扣 144. 二叉树的前序遍历

题目来源:https://leetcode.cn/problems/binary-tree-preorder-traversal/description/

C++题解1:递归算法。注意递归函数的参数和返回值、终止条件、单层递归的逻辑。

递归函数的参数是当前指针和用来存放的vector,注意vector要加&引用;终止条件为当前遍历节点为空;前序遍历是指中间节点在前面,即中左右。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
private:    
    void search(TreeNode* cur, vector<int>& result){
        if(cur == nullptr) return;
        result.push_back(cur->val);
        search(cur->left, result);
        search(cur->right, result);
    }

public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> result;
        search(root, result);
        return result;
    }
};

C++题解2:迭代遍历。使用栈实现。

由于前序遍历是中左右,那对应的入栈顺序就应该是右左中,不过中可以不入栈,直接获取其val进行保存;当遇到中为null时,意味着没有左右子树,此时只要将该节点pop出来就好。

class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        stack<TreeNode*> store;
        vector<int> result;
        TreeNode* cur = root, next;
        while(cur != nullptr || !store.empty()){
            if(cur != nullptr){
                store.push(cur->right);
                store.push(cur->left);
                result.push_back(cur->val);
            }
            cur = store.top();
            store.pop();
        }
        return result;
    }
};

C++提交3:统一迭代法。用空节点来标记待处理的中间节点。参照代码随想录

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值