Binary Tree Postorder Traversal

来源:互联网 发布:七匣子淘宝 编辑:程序博客网 时间:2024/06/11 11:45

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].

递归实现:

public List<Integer> postorderTraversal(TreeNode root) {List<Integer> result=new ArrayList<Integer>();if(root==null)return result;result.addAll(postorderTraversal(root.left));result.addAll(postorderTraversal(root.right));result.add(root.val);return result;}

循环实现:

public List<Integer> postorderTraversal(TreeNode root) {ArrayList<Integer> result = new ArrayList<Integer>();Stack<TreeNode> stack = new Stack<TreeNode>();TreeNode prev = null; // previously traversed nodeTreeNode curr = root;if (root == null) return result;stack.push(root);while (!stack.empty()) {curr = stack.peek();if (prev == null || prev.left == curr || prev.right == curr) { // traverse down the treeif (curr.left != null) stack.push(curr.left);else if (curr.right != null)stack.push(curr.right);} else if (curr.left == prev) { // traverse up the tree from the leftif (curr.right != null) stack.push(curr.right);} else { // traverse up the tree from the rightresult.add(curr.val);stack.pop();}prev = curr;}return result;}


0 0
原创粉丝点击