Skip to content

Latest commit

 

History

History
63 lines (46 loc) · 1.4 KB

144-binary-tree-preorder-traversal.md

File metadata and controls

63 lines (46 loc) · 1.4 KB

144. Binary Tree Preorder Traversal - 二叉树的前序遍历

给定一个二叉树,返回它的 前序 遍历。

 示例:

输入: [1,null,2,3]  
   1
    \
     2
    /
   3 

输出: [1,2,3]

进阶: 递归算法很简单,你可以通过迭代算法完成吗?


题目标签:Stack / Tree

题目链接:LeetCode / LeetCode中国

题解

Language Runtime Memory
cpp 0 ms 884.7 KB
/**
 * 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> res;
    void preorder(TreeNode* node) {
        if (!node) return;
        res.push_back(node->val);
        preorder(node->left);
        preorder(node->right);
    }

    vector<int> preorderTraversal(TreeNode* root) {
        preorder(root);
        return res;
    }
};
static auto _ = [](){ ios::sync_with_stdio(false); cin.tie(nullptr); return 0; }();