题目:

二叉树的后序遍历

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

样例

给出一棵二叉树 {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. C++版 - LeetCode 145: Binary Tree Postorder Traversal(二叉树的后序遍历,迭代法)

    145. Binary Tree Postorder Traversal Total Submissions: 271797 Difficulty: Hard 提交网址: https://leetco ...

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

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

  4. LeetCode 145. Binary Tree Postorder Traversal 二叉树的后序遍历 C++

    Given a binary tree, return the postorder traversal of its nodes' values. Example: Input: [,,] \ / O ...

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

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

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

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

  7. [leetcode] 94. Binary Tree Inorder Traversal 二叉树的中序遍历

    题目大意 https://leetcode.com/problems/binary-tree-inorder-traversal/description/ 94. Binary Tree Inorde ...

  8. [LeetCode] 94. Binary Tree Inorder Traversal(二叉树的中序遍历) ☆☆☆

    二叉树遍历(前序.中序.后序.层次.深度优先.广度优先遍历) 描述 解析 递归方案 很简单,先左孩子,输出根,再右孩子. 非递归方案 因为访问左孩子后要访问右孩子,所以需要栈这样的数据结构. 1.指针 ...

  9. LeetCode 94. Binary Tree Inorder Traversal 二叉树的中序遍历 C++

    Given a binary tree, return the inorder traversal of its nodes' values. Example: Input: [,,] \ / Out ...

随机推荐

  1. va_list深究

    va_list深究 2011-04-21 21:06:11|  分类: C/C++|字号 订阅     VA函数(variable argument function),参数个数可变函数,又称可变参数 ...

  2. PHP学习笔记:万能随机字符串生成函数(已经封装好)

    做验证码用到的,然后就把这个函数封装起来,使用时候要设置2个参数: $str设置里要被采集的字符串,比如: $str='efasfgzsrhftjxjxjhsrth'; 则在函数里面生成的字符串就回从 ...

  3. FOOD

    Serving order of food courses(上菜顺序)1. Appetizer(starter)2. Main Course3. Dessert Style of cooking1. ...

  4. IBM

    http://www.ibm.com/developerworks/cn/data/library/techarticle/dm-1306mongodb2/

  5. POJ1942 Paths on a Grid(组合)

    题目链接. 分析: #include <cstdio> #include <iostream> #include <map> #include <cstrin ...

  6. python bottle框架(WEB开发、运维开发)教程

    教程目录 一:python基础(略,基础还是自己看书学吧) 二:bottle基础 python bottle web框架简介 python bottle 框架环境安装 python bottle 框架 ...

  7. 12c meet sysdba meet ORA-01017: invalid username/password; logon denied

    checklist: 1.12c: threaded_execution=true Prevents OS Login As Sysdba 2. The following database para ...

  8. 我的学习之路_第五章_Data,正则

    Date 类 (时间类) 所属包:java.util.Date 构造方法: public Date() 返回的是当前时间 也就是1970-1-1到电脑目前的时间值,用毫秒来表示 public Date ...

  9. Linux(centos7)下安装Docker

    近期公司开始推Docker技术.这个系列的文章都是基于CentOS7系统下进行讲解的. Docker简介 Docker 是一个开源的应用容器引擎,让开发者可以打包他们的应用以及依赖包到一个可移植的容器 ...

  10. GC频繁抖动的主要原因

    内存抖动 内存抖动是因为大量的对象被创建又在短时间内马上被释放,如循环中分配对象,很容易引起GC,特别是在较大的循环次数或者一个循环中分配较多的临时对象时. 瞬间产生大量的对象 瞬间产生大量的对象,即 ...