LeetCode 145. Binary Tree Postorder Traversal

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

v2-33d4ea3c44a787b89bea684d5a01b9b9_1440w.jpg

Description



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


Example:


Input: [1,null,2,3]
   1
    \
     2
    /
   3
Output: [3,2,1]
Follow up: Recursive solution is trivial, could you do it iteratively?


描述



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


示例:


输入: [1,null,2,3]  
   1
    \
     2
    /
   3 
输出: [3,2,1]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?


思路



  • 使用栈来模拟递归.
  • 后序遍历要注意弹出的条件,当一个节点的左右子树为空或者左右子树都已经遍历过了的时候,此节点就应当被弹出.
  • 我们用个last表示上一次被弹出的节点,如果last是当前节点node的子节点,说明node的左右子节点都已经遍历完毕(在栈中我们先压入niode节点,再压入node右节点,最后压入左节点,则last如果是node子节点,无论是左节点还是右节点,则node子树都遍历完了).


# -*- coding: utf-8 -*-
# @Author:             何睿
# @Create Date:        2019-01-12 19:30:10
# @Last Modified by:   何睿
# @Last Modified time: 2019-01-12 19:42:54
# 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):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if not root:
            return []
        last, res, stack = root, [], [root]
        while stack:
            # top 指向栈顶元素
            top = stack[-1]
            # 栈顶元素弹出的条件是其左右子树同时为空或者其左右子树已经遍历过了
            if (not top.left and not top.right) or (last == top.right or last == top.left):
                top = stack.pop()
                res.append(top.val)
                last = top
            else:
                # 根据栈的特性,先进的元素后出
                if top.right:
                    stack.append(top.right)
                # 后进的元素先出
                if top.left:
                    stack.append(top.left)
        return res


源代码文件在这里.


目录
相关文章
|
6月前
|
Java
Leetcode 114. Flatten Binary Tree to Linked List
思路也很简单,先把root的左子树(如有)变成单链表 leftlinkedlist,把root的右子树(如有)变成单链表 rightlinkedlist,再把root的右节点变成leftlikedlist,再把rightlinkedlist接到leftlinkedlist后面,代码如下。
21 1
|
6月前
Leetcode Minimum Depth of Binary Tree (面试题推荐)
计算树的最小深度 很简单的一道题,只需要遍历一次树,到叶子节点的时候计算一下深度和当前最小深度比较,保存最小值就行。 我在这用了一个全局变量 mindepth。总感觉我这代码写的不够简练,求更精简的方法。
26 0
|
6月前
Leetcode Binary Tree Postorder Traversal(面试题推荐)
非递后续归遍历二叉树,肯定得用到栈。先序遍历很好写,但后续遍历就不是那么容易了。 只需要设置个指针pre,指向最后输出的那个节点就行了,只要判断cur指针指向的是上次输出节点的父节点,且cur无其他未遍历的节点,这个时候就把cur节点输出即可,然后更改pre。原理是要遍历当前节点,其所有子节点都必须遍历完,因为肯定是先左后右,所以只需一个指针保持前一次输出的结果即可。
25 0
|
6月前
Leetcode 236. Lowest Common Ancestor of a Binary Tree
根据LCA的定义,二叉树中最小公共祖先就是两个节点p和q最近的共同祖先节点,LCA的定义没什么好解释的,主要是这道题的解法。
16 0
|
6月前
Leetcode 623. Add One Row to Tree
题目很简单,在树的第d层加一层,值为v。递归增加一层就好了。代码如下
26 0
LeetCode contest 190 5418. 二叉树中的伪回文路径 Pseudo-Palindromic Paths in a Binary Tree
LeetCode contest 190 5418. 二叉树中的伪回文路径 Pseudo-Palindromic Paths in a Binary Tree
|
算法 Python
LeetCode 108. 将有序数组转换为二叉搜索树 Convert Sorted Array to Binary Search Tree
LeetCode 108. 将有序数组转换为二叉搜索树 Convert Sorted Array to Binary Search Tree
LeetCode 102. 二叉树的层序遍历 Binary Tree Level Order Traversal
LeetCode 102. 二叉树的层序遍历 Binary Tree Level Order Traversal
|
6天前
|
算法 C++
【刷题】Leetcode 1609.奇偶树
这道题是我目前做过最难的题,虽然没有一遍做出来,但是参考大佬的代码,慢慢啃的感觉的真的很好。刷题继续!!!!!!
9 0
|
6天前
|
算法 索引
【刷题】滑动窗口精通 — Leetcode 30. 串联所有单词的子串 | Leetcode 76. 最小覆盖子串
经过这两道题目的书写,相信大家一定深刻认识到了滑动窗口的使用方法!!! 下面请大家继续刷题吧!!!
13 0