LeetCode 145 Binary Tree Postorder Traversal

来源:互联网 发布:人工智能伏羲觉醒种子 编辑:程序博客网 时间:2024/06/05 02:23

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

For example:
Given binary tree {1,#,2,3},

   1    \     2    /   3

return [3,2,1].

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

方法一 递归

public List<Integer> postorderTraversal2(TreeNode root) {List<Integer> result = new ArrayList<>();postorderTraversal(root, result);return result;}public void postorderTraversal(TreeNode root, List<Integer> list) {if (root == null) return;if (root.left != null) postorderTraversal(root.left, list);if (root.right != null) postorderTraversal(root.right, list);list.add(root.val);}
方法二: 后序遍历是 左 右 根 的顺序,所以我们现在进行 根 右 左 的顺序,最后倒序过来 就是想要的左右根的顺序了

public List<Integer> postorderTraversal(TreeNode root) {List<Integer> list = new ArrayList<>();if (root == null) return list;Stack<TreeNode> stack = new Stack<>();stack.push(root);while (!stack.isEmpty()) {TreeNode tmp = stack.pop();list.add(tmp.val);if (tmp.left != null) stack.push(tmp.left);if (tmp.right != null) stack.push(tmp.right);}Collections.reverse(list);return list;}

方法三 使用 LinkedList 

public List<Integer> postorderTraversal6(TreeNode root) {LinkedList<Integer> list = new LinkedList<>();if (root == null) return list;Stack<TreeNode> stack = new Stack<>();stack.push(root);while (!stack.isEmpty()) {TreeNode temp = stack.pop();list.addFirst(temp.val);if (temp.left != null) stack.push(temp.left);if (temp.right != null) stack.push(temp.right);}return list;}

方法四:如果node的孩子已经入栈,那么就把node的对应孩子置为空,防止后续访问此节点时,不知是该入栈其孩子,还是出栈此节点

public List<Integer> postorderTraversal3(TreeNode root) {List<Integer> res = new ArrayList<Integer>();if (root == null) return res;Stack<TreeNode> stack = new Stack<TreeNode>();stack.push(root);while (!stack.isEmpty()) {TreeNode temp = stack.peek();if (temp.left == null && temp.right == null) {TreeNode pop = stack.pop();res.add(pop.val);} else {if (temp.right != null) {stack.push(temp.right);temp.right = null;//这步很巧妙}if (temp.left != null) {stack.push(temp.left);temp.left = null;}}}return res;}

方法四:不借助于栈http://www.cnblogs.com/yrbbest/p/4489571.html

public List<Integer> postorderTraversal4(TreeNode root) {List<Integer> res = new LinkedList<>();TreeNode node = root, succ;while (node != null) {if (node.right == null) {res.add(0, node.val);node = node.left;} else {succ = node.right;while (succ.left != null && succ.left != node) {succ = succ.left;}if (succ.left == null) {succ.left = node;res.add(0, node.val);node = node.right;} else {succ.left = null;node = node.left;}}}return res;}




http://blog.csdn.net/crazy1235/article/details/51494797

0 0
原创粉丝点击