LeetCode 145.二叉树的后序遍历

题目描述

给定一个二叉树,返回它的 后序 遍历
在这里插入图片描述

解题思路

  • 递归法

Cpp实现

/**
 * 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;
    vector<int> postorderTraversal(TreeNode* root) {
        if(root){
            if(root->left)
            postorderTraversal(root->left);
            if(root->right)
            postorderTraversal(root->right);
            res.push_back(root->val);
        }
        return res;

    }
};

在这里插入图片描述

Python实现

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

class Solution:
    def postorderTraversal(self, root: TreeNode) -> List[int]:
        res = []
        def dfs(root):
            if not root:
                return
            if root.left:
                dfs(root.left)
            if root.right:
                dfs(root.right)
            res.append(root.val)
        dfs(root)
        return res

在这里插入图片描述

发布了73 篇原创文章 · 获赞 2 · 访问量 3145

猜你喜欢

转载自blog.csdn.net/soulmate______/article/details/105222284