145 Binary Tree Postorder Traversal 二叉树的后序遍历
给定一棵二叉树,返回其节点值的后序遍历。
例如:
给定二叉树 [1,null,2,3],
1
\
2
/
3
返回 [3,2,1]。
注意: 递归方法很简单,你可以使用迭代方法来解决吗?
详见:https://leetcode.com/problems/binary-tree-postorder-traversal/description/
Java实现:
递归实现:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<Integer> postorderTraversal(TreeNode root) { List<Integer> res=new ArrayList<Integer>(); if(root==null){ return res; } return postorderTraversal(root,res); } private List<Integer> postorderTraversal(TreeNode root,List<Integer> res){ if(root==null){ return res; } postorderTraversal(root.left,res); postorderTraversal(root.right,res); res.add(root.val); return res; } }
非递归实现:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public List<Integer> postorderTraversal(TreeNode root) { List<Integer> res=new ArrayList<Integer>(); if(root==null){ return res; } Stack<TreeNode> stk1=new Stack<TreeNode>(); Stack<TreeNode> stk2=new Stack<TreeNode>(); stk1.push(root); while(!stk1.isEmpty()){ root=stk1.pop(); stk2.push(root); if(root.left!=null){ stk1.push(root.left); } if(root.right!=null){ stk1.push(root.right); } } while(!stk2.isEmpty()){ res.add(stk2.pop().val); } return res; } }