题目:
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 static List<Integer> result=new ArrayList<Integer>(); public static List<Integer> postorderTraversal(TreeNode root) { if(root!=null) { postorderTraversal(root.right); postorderTraversal(root.left); result.add(root.val); } return result; }
迭代的稍微复杂一些 总体上和前面的解法是一样的 不过这边要先访问左右节点,同样还是以左节点作为主线,不过这里要增加一个栈记录每个节点的右节点是否已经被访问过,只有当左右节点都被访问的前提下才能访问根节点
public static List<Integer> postorderTraversal2(TreeNode root) { List<Integer> res=new ArrayList<>(); Stack<TreeNode> nodeStack=new Stack<>(); Stack<Integer> nodeState=new Stack<>();//记录右节点是否已经访问过,1表示已经访问了,0表示未访问 if(root==null) return res; else { nodeStack.push(root); nodeState.push(0); root=root.left; } while(!nodeStack.isEmpty()) { while(root!=null) { nodeStack.push(root); nodeState.push(0); root=root.left; }//当这个循环跳出的时候 说明nodeStak栈顶的那个节点没有左节点 if(nodeState.peek()==1)//如果这时候已经访问过右节点了 这时候就可以访问根节点 { res.add(nodeStack.pop().val); nodeState.pop();//把根节点对应的状态值去除 } else {//访问右节点 root=nodeStack.peek().right; nodeState.pop();//更改状态值 由0变1 nodeState.push(1); } } return res; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-08-09 23:31:14