2021年2月25日 星期四

LeetCode 144. Binary Tree Preorder Traversal [Medium] [C++] 解題筆記

 Given the root of a binary tree, return the preorder traversal of its nodes' values.

 

Example 1:

Input: root = [1,null,2,3]
Output: [1,2,3]

Example 2:

Input: root = []
Output: []

Example 3:

Input: root = [1]
Output: [1]

Example 4:

Input: root = [1,2]
Output: [1,2]

Example 5:

Input: root = [1,null,2]
Output: [1,2]
想法:
    這題要我們求給定的 tree 的前序遍歷,用 recursive 非常簡單就可以實現,而 iterative 的話就是利用 stack 來紀錄
目前遍歷到的 node 也不難,先寫 recursive 的解,有空再寫 iterative的解法。

完整程式碼:
class Solution {
public:
    vector<int> preorder;
    vector<int> preorderTraversal(TreeNode* root) {
        if (root == nullptr) { return preorder; }
        preorder.push_back(root->val);
        preorderTraversal(root->left);
        preorderTraversal(root->right);
        return preorder;
    }
};


沒有留言:

張貼留言