给定一棵二叉树,返回其节点值的后序遍历。
例如:给定二叉树 [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 ListpostorderTraversal(TreeNode root) { List res=new ArrayList (); if(root==null){ return res; } return postorderTraversal(root,res); } private List postorderTraversal(TreeNode root,List 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 ListpostorderTraversal(TreeNode root) { List res=new ArrayList (); if(root==null){ return res; } Stack stk1=new Stack (); Stack stk2=new Stack (); 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; }}