[LeetCode]Binary Tree Postorder Traversal,解题报告
2013-12-02 14:49
344 查看
题目
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 解题报告
- LeetCode 解题报告 Binary Tree Postorder Traversal
- LeetCode解题报告:Binary Tree Postorder Traversal
- LeetCode: Construct Binary Tree from Inorder and Postorder Traversal 解题报告
- [Leetcode] 106. Construct Binary Tree from Inorder and Postorder Traversal 解题报告
- leetCode解题报告之Binary Tree Postorder Traversal
- [leetcode] 106. Construct Binary Tree from Inorder and Postorder Traversal 解题报告
- 【LeetCode】Construct Binary Tree from Inorder and Postorder Traversal 解题报告
- LeetCode 145:Binary Tree Postorder Traversal 解题与思考
- LeetCode: Binary Tree Inorder Traversal 解题报告
- leetCode解题报告之Binary Tree Level Order Traversal II,I(二叉树层次遍历)
- 【LeetCode】Construct Binary Tree from Preorder and Inorder Traversal 解题报告
- 【LeetCode】Binary Tree Level Order Traversal II 解题报告
- LeetCode: Binary Tree Level Order Traversal 解题报告
- LeetCode解题报告—— Unique Binary Search Trees & Binary Tree Level Order Traversal & Binary Tree Zigzag Level Order Traversal
- LeetCode 解题报告 Binary Tree Preorder Traversal
- 【LeetCode】144 . Binary Tree Preorder Traversal 解题报告
- Leetcode 105. Construct Binary Tree from Preorder and Inorder Traversal 先序和中序中恢复二叉树 解题报告
- [LeetCode OJ] Binary Tree Postorder Traversal 解题报告
- 【LeetCode】 Binary Tree Zigzag Level Order Traversal 解题报告