题目:

二叉树的后序遍历

给出一棵二叉树,返回其节点值的后序遍历。

样例

给出一棵二叉树 {1,#,2,3},

   1
    \
     2
    /
   3

返回 [3,2,1]

挑战

你能使用非递归实现么?

解题:

递归程序好简单

Java程序:

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: Postorder in ArrayList which contains node values.
     */
    public ArrayList<Integer> postorderTraversal(TreeNode root) {
        // write your code here
        ArrayList<Integer> res = new ArrayList<Integer>();
        res = postorder(res,root);
        return res;
    }
    public ArrayList<Integer> postorder(ArrayList<Integer> res,TreeNode root){
        if(root==null)
            return res;
        if(root.left!=null)
            res = postorder(res,root.left);
        if(root.right!=null)
            res = postorder(res,root.right);
        res.add(root.val);
        return res;
    }
}

总耗时: 1210 ms

Python程序:

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""

class Solution:
    """
    @param root: The root of binary tree.
    @return: Postorder in ArrayList which contains node values.
    """
    def postorderTraversal(self, root):
        # write your code here
        res = []
        res = self.postorder(res,root)
        return res

    def postorder(self,res,root):
        if root==None:
            return res
        if root.left!=None:
            res = self.postorder(res,root.left)
        if root.right!=None:
            res = self.postorder(res,root.right)
        res.append(root.val)
        return res

总耗时: 380 ms

非递归程序,直接来源

Java程序:

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: Postorder in ArrayList which contains node values.
     */
    public ArrayList<Integer> postorderTraversal(TreeNode root) {
        // write your code here
        int a = 1;
        ArrayList<TreeNode> s = new ArrayList<TreeNode>();
        ArrayList<Integer> res = new ArrayList<Integer>();
        if (root == null) return res;
        while(a == 1){
            while(root.left != null || root.right != null){
                if (root.left != null){
                    s.add(root);
                    root = root.left;
                }
                else{
                    s.add(root);
                    root = root.right;
                }
            }
            TreeNode y = s.get(s.size()-1);
            while (root == y.right || y.right == null){
                res.add(root.val);
                s.remove(s.size()-1);
                if (s.size() == 0){
                    a = 0;
                    res.add(y.val);
                    break;
                }
                root = y;
                y = s.get(s.size()-1);
            }
            if (root == y.left && y.right != null){
                res.add(root.val);
                root = y.right;
            }
        }
        return res;
    }
}

总耗时: 1388 ms

Python程序:

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""

class Solution:
    """
    @param root: The root of binary tree.
    @return: Postorder in ArrayList which contains node values.
    """
    def postorderTraversal(self, root):
        # write your code here
        a = 1
        s = [root]
        res = []
        if root is None:
            return res[1:1]
        while a == 1:
            while root.left is not None or root.right is not None:
                if root.left is not None:
                    s.append(root)
                    root = root.left
                else:
                    s.append(root)
                    root = root.right
            y = s[len(s)-1]
            while root == y.right or y.right is None:
                res.append(root.val)
                del s[len(s)-1]
                if len(s) == 1:
                    a = 0
                    res.append(y.val)
                    break
                root = y
                y = s[len(s)-1]
            if root == y.left and y.right is not None:
                res.append(root.val)
                root = y.right
        return res 

总耗时: 360 ms

lintcode:Binary Tree Postorder Traversal 二叉树的后序遍历的更多相关文章

  1. [LeetCode] Binary Tree Postorder Traversal 二叉树的后序遍历

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

  2. leetcode题解:Binary Tree Postorder Traversal (二叉树的后序遍历)

    题目: Given a binary tree, return the postorder traversal of its nodes' values. For example:Given bina ...

  3. [LeetCode] Binary Tree Inorder Traversal 二叉树的中序遍历

    Given a binary tree, return the inorder traversal of its nodes' values. For example:Given binary tre ...

  4. [LeetCode] Binary Tree Preorder Traversal 二叉树的先序遍历

    Given a binary tree, return the preorder traversal of its nodes' values. For example:Given binary tr ...

  5. leetcode Binary Tree Postorder Traversal 二叉树后续遍历

    先给出递归版本的实现方法,有时间再弄个循环版的.代码如下: /** * Definition for binary tree * struct TreeNode { * int val; * Tree ...

  6. 12. Binary Tree Postorder Traversal &amp;&amp; Binary Tree Preorder Traversal

    详见:剑指 Offer 题目汇总索引:第6题 Binary Tree Postorder Traversal            Given a binary tree, return the po ...

  7. LeetCode Binary Tree Postorder Traversal(数据结构)

    题意: 用迭代法输出一棵二叉树的后序遍历结果. 思路: (1)用两个栈,一个存指针,一个存标记,表示该指针当前已经访问过哪些孩子了. /** * Definition for a binary tre ...

  8. Binary Tree Preorder Traversal and Binary Tree Postorder Traversal

    Binary Tree Preorder Traversal Given a binary tree, return the preorder traversal of its nodes' valu ...

  9. 【leetcode】Binary Tree Postorder Traversal (hard) ☆

    二叉树的后序遍历 用标记右子树vector的方法 vector<int> postorderTraversal(TreeNode *root) { vector<int> an ...

随机推荐

  1. div的水平和垂直居中

    CSS实现div的水平居中 div的水平居中可以通过margin设置为0 auto实现. .myDiv { width: 200px; height: 100px; margin: 0 auto; } ...

  2. iOS Start developing ios apps (OC) pdf

    这是苹果官方最后一次更新的基于OC的iOS开发基础教程, 如果英文的看不懂,还有中文的版本哦. 点击下面的链接 好东西,分享给大家! 如果确实有帮到你,麻烦star一下我的github吧!

  3. Castle Windsor常用介绍以及其在ABP项目的应用介绍

    最近在研究ABP项目,有关ABP的介绍请看阳光铭睿 博客,ABP的DI和AOP框架用的是Castle Windsor下面就对Castle Windsor项目常用方法介绍和关于ABP的使用总结 1.下载 ...

  4. 教务管理系统数据库E/R图

  5. WebRTC源码分析四:视频模块结构

    转自:http://blog.csdn.net/neustar1/article/details/19492113 本文在上篇的基础上介绍WebRTC视频部分的模块结构,以进一步了解其实现框架,只有了 ...

  6. Screen-后台运行

    文章转自:http://www.cnblogs.com/mchina/archive/2013/01/30/2880680.html 本来想搜集资料写一个的,结果发现该博主已经总结的很好,条理清晰. ...

  7. P2763: [JLOI2011]飞行路线

    然而WA了呀,这道分层图,也是不明白为什么WA了=-= ; maxn=; points=; type node=record f,t,l:longint; end; var n,m,k,i,j,u,v ...

  8. 【英语】Bingo口语笔记(5) - 英式和美式英语的发音区别

  9. 【模拟】Codeforces 671B Robin Hood

    题目链接: http://codeforces.com/problemset/problem/671/B 题目大意: N个人,每个人有Ci钱,现在有一个人劫富济贫,从最富的人之一拿走1元,再给最穷的人 ...

  10. HAProxy、Nginx 配置 HTTP/2 完整指南

    基于最近对HTTP/2的争论和它的优势,是时候升级底层架构了.这篇文章将会介绍如何在安装和配置HAProxy和Ngnix(使用ssl终端).为了简化流程,我建议你准备好使用Docker镜像. 如果你想 ...