开始看了中序遍历觉得后序遍历的非递归方法也会很容易,而后自己开始尝试编写程序,发现并不是这样的后序遍历的实现很复杂
直接放代码
Java版的递归调用
/** * Definition of TreeNode: * public class TreeNode { * public int val; * public TreeNode left, right; * public TreeNode(int val) { * this.val = val; * this.left = this.right = null; * } * } */ public class Solution { /* * @param root: A Tree * @return: Postorder in ArrayList which contains node values. */ public List<Integer> postorderTraversal(TreeNode root) { LinkedList<Integer> targetList = new LinkedList<>(); if(root == null) return null; if(root.left!=null) targetList.addAll(postorderTraversal(root.left)); if(root.right!=null) targetList.addAll(postorderTraversal(root.right)); targetList.add(root.val); return targetList; } }
递归版的非常的容易,在此不在讲解
下面放上非递归版的代码
Python版非递归:
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param: root: A Tree @return: Postorder in ArrayList which contains node values. """ def postorderTraversal(self, root): if root is None: return [] temp = [] #用栈结构存储节点 target = [] #结果列表 last = None #用来存储最后的节点 cur = root while cur is not None: #循环遍历到左子树底 temp.append(cur) cur = cur.left while len(temp) > 0: cur = temp.pop() #出栈 if cur.right is None or last is cur.right: #这里进行判断,若当前的根节点没有右子树,或者当前的节点的右节点已经被标注成使用过的节点 target.append(cur.val) last = cur #将当前的节点标注成使用过的节点 else: temp.append(cur) #如果不是则将根节点放回temp中继续遍历右子树 cur = cur.right while cur is not None:#右子树继续遍历左子树 temp.append(cur)#入栈 cur = cur.left return target
每次一定要去努力思考再去借鉴别人的思路!!!!!!!!