145. Binary Tree Postorder Traversal
給定一個二叉樹的根節點,返回其節點值的後序遍歷結果。
範例 :
輸入: root = [1, null, 2, 3] 輸出: [3, 2, 1]
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 postorderTraversal(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 postorder traversal
def traverse(node):
if node is not None:
traverse(node.left) # Recursively visit the left subtree
traverse(node.right) # Recursively visit the right subtree
result.append(node.val) # Visit the root node
# Start the traversal from the root node
traverse(root)
return result
16.68MB, 36ms
C++
#include <vector>
using namespace std;
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
postorderHelper(root, result);
return result;
}
private:
void postorderHelper(TreeNode* node, vector<int>& result) {
if (node == nullptr) {
return;
}
postorderHelper(node->left, result); // Recursively visit the left subtree
postorderHelper(node->right, result); // Recursively visit the right subtree
result.push_back(node->val); // Visit the root node
}
};
9.81MB, 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 postorderTraversal = function(root) {
const result = [];
const traverse = (node) => {
if (node === null) {
return;
}
traverse(node.left); // Recursively visit the left subtree
traverse(node.right); // Recursively visit the right subtree
result.push(node.val); // Visit the root node
};
traverse(root);
return result;
};
48.91MB, 46ms