王廷瑋|數位醫療|智慧醫療: 144. Binary Tree Preorder Traversal WFU

2024年7月7日 星期日

144. Binary Tree Preorder Traversal

144. Binary Tree Preorder Traversal


給定一個二叉樹的根節點,返回其節點值的前序遍歷結果。

範例 :

輸入: root = [1,null,2,3] 輸出: [1,2,3]


Python


from typing import Optional, List

# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right

class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
# If the root node is None, return an empty list
if root is None:
return []

# Initialize the result list
result = []

# Define the recursive function for preorder traversal
def traverse(node):
if node is not None:
result.append(node.val) # Visit the root node
traverse(node.left) # Recursively visit the left subtree
traverse(node.right) # Recursively visit the right subtree

# Start the traversal from the root node
traverse(root)

return result

16.54MB, 42ms


C++


#include <vector>
using namespace std;

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

private:
void preorderHelper(TreeNode* node, vector<int>& result) {
if (node == nullptr) {
return;
}
result.push_back(node->val); // Visit the root node
preorderHelper(node->left, result); // Recursively visit the left subtree
preorderHelper(node->right, result); // Recursively visit the right subtree
}
};

9.90MB, 0ms


Javascript


/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val === undefined ? 0 : val)
* this.left = (left === undefined ? null : left)
* this.right = (right === undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var preorderTraversal = function(root) {
const result = [];
const traverse = (node) => {
if (node === null) {
return;
}
result.push(node.val); // Visit the root node
traverse(node.left); // Recursively visit the left subtree
traverse(node.right); // Recursively visit the right subtree
};
traverse(root);
return result;
};

48.84MB, 42ms