【第22期】观点:IT 行业加班,到底有没有价值?

[LeetCode]Binary Tree Postorder Traversal,解题报告

原创 2013年12月02日 14:49:46

题目

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

Note: Recursive solution is trivial, could you do it iteratively?

思路

题目给的Note提示,意思是用非递归实现二叉树的后序遍历

之前用c很详细的描述过二叉树各种递归、非递归遍历,想了解原理的同学移步:http://blog.csdn.net/wzy_1988/article/details/8450952


AC代码

import java.util.ArrayList;
import java.util.LinkedList;

public class BinaryTreePostorderTraversal {
    static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int x) {
            this.val = x;
        }
    }

    public static ArrayList<Integer> postorderTraversal(TreeNode root) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        LinkedList<TreeNode> stack = new LinkedList<TreeNode>();
        TreeNode pre = null;
        
        while (!stack.isEmpty() || root != null) {
            if (root != null) {
                stack.addFirst(root);
                root = root.left;
            } else {
                root = stack.removeFirst();
                if (root.right == null || root.right == pre) {
                    pre = root;
                    list.add(root.val);
                    root = null;
                } else {
                    stack.addFirst(root);
                    root = root.right;
                }
            }
        }
        
        return list;
    }
}


后记

二叉树的非递归后序遍历应该算是遍历中还稍微有点难度的,这个看懂了相信非递归前序、中序遍历都不是问题,加油
版权声明:本文为博主原创文章,未经博主允许不得转载。 举报

相关文章推荐

leetCode解题报告之Binary Tree Postorder Traversal

题目: Binary Tree Postorder Traversal   Given a binary tree, return the postorder travers...

[LeetCode]*106.Construct Binary Tree from Inorder and Postorder Traversal

题目 Given inorder and postorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. 思路 ...

程序员升职加薪指南!还缺一个“证”!

CSDN出品,立即查看!

[leetcode] 145. Binary Tree Postorder Traversal 解题报告

题目链接:https://leetcode.com/problems/binary-tree-postorder-traversal/ Given a binary tree, return th...

[LeetCode]145.Binary Tree Postorder Traversal

【题目】 Given a binary tree, return thepostordertraversal

[Leetcode] 106. Construct Binary Tree from Inorder and Postorder Traversal 解题报告

题目: Given inorder and postorder traversal of a tree, construct the binary tree. Note: You may ass...
收藏助手
不良信息举报
您举报文章:深度学习:神经网络中的前向传播和反向传播算法推导
举报原因:
原因补充:

(最多只允许输入30个字)