Leetcode:144.二叉树的先序遍历

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

 示例:

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

输出: [1,2,3]

解题思路:

先序遍历:1.访问根节点。2.访问左子树。3.访问右子树。

C++代码
class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        if (root == NULL) return{};
        DFS(root);
        return res;
    }
    void DFS(TreeNode* root) {
        if (root == NULL) return;
        res.push_back(root->val);
        if (hasLChild(root)) DFS(root->left);
        if (hasRChild(root)) DFS(root->right);
    }
private:
    vector<int> res;
};

猜你喜欢

转载自blog.csdn.net/qq_23523409/article/details/83755110