Leetcode|二叉树的遍历方式|144. 二叉树的前序遍历

2021-09-18 15:26:24 浏览数 (1)

1 分治法-递归

代码语言:javascript复制
/**
 * 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 {
public:
    void dfs(TreeNode* root, vector<int>& vec) {
        if (!root) return;
        vec.push_back(root->val);
        dfs(root->left, vec);
        dfs(root->right, vec);
    }
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> vec;
        dfs(root, vec);
        return vec;
    }
};

2 迭代法-栈

代码语言:javascript复制
class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        if (!root) return {};
        vector<int> vec;
        stack<TreeNode*> stk;
        auto node = root;
        
        while (!stk.empty() || node) {
            // 1.遍历到最左子节点
            while (node) {
                vec.emplace_back(node->val);
                stk.emplace(node);
                node = node->left;
            }
            // 2.遍历最左子节点的右子树
            node = stk.top(); stk.pop();
            node = node->right;
        }
        return vec;
    }
};

0 人点赞