前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >leecode刷题(30)-- 二叉树的后序遍历

leecode刷题(30)-- 二叉树的后序遍历

作者头像
希希里之海
发布2019-05-15 10:32:52
3050
发布2019-05-15 10:32:52
举报
文章被收录于专栏:weixuqin 的专栏weixuqin 的专栏

leecode刷题(30)-- 二叉树的后序遍历

二叉树的后序遍历

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

示例:

代码语言:javascript
复制
输入: [1,null,2,3]  
   1
    \
     2
    /
   3 

输出: [3,2,1]

思路

跟上道题一样,我们使用递归的思想解决。

后序遍历:

先处理左子树,然后是右子树,最后是根

代码如下

Java 描述

代码语言:javascript
复制
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    List<Integer> list = new ArrayList();
    public List<Integer> postorderTraversal(TreeNode root) {
        if (root != null) {
            postorderTraversal(root.left);
            postorderTraversal(root.right);
            list.add(root.val);
        }
        return list;
    }
}

python 描述

代码语言:javascript
复制
# 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 = []
        if root is not None:
            res = res + self.postorderTraversal(root.left)
            res = res + self.postorderTraversal(root.right)
            res = res + [root.val]      
        return res

总结

对比如下:

image.png
image.png
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-05-06 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • leecode刷题(30)-- 二叉树的后序遍历
    • 二叉树的后序遍历
      • 思路
        • 代码如下
          • 总结
          领券
          问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档