LeetCode145 Binary Tree Postorder Traversal Java题解(递归 迭代)
来源:互联网 发布:js svg transform 编辑:程序博客网 时间:2024/06/05 17:26
题目:
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; }
0 0
- LeetCode145 Binary Tree Postorder Traversal Java题解(递归 迭代)
- LeetCode145 Binary Tree Postorder Traversal(迭代实现) Java
- Binary Tree Postorder Traversal leetcode145
- LeetCode145:Binary Tree Postorder Traversal
- LeetCode145-Binary-Tree-Postorder-Traversal
- LeetCode145. Binary Tree Postorder Traversal
- leetcode145. Binary Tree Postorder Traversal
- LeetCode145—Binary Tree Postorder Traversal
- Leetcode145——Binary Tree Postorder Traversal
- LeetCode145. Binary Tree Postorder Traversal(hard)
- LeetCode144 Binary Tree PreOrder Traversal Java题解(递归 迭代)
- Binary Tree Postorder Traversal(迭代写法)
- Leetcode145: Construct Binary Tree from Inorder and Postorder Traversal
- LeetCode145——Binary Tree Postorder Traversal二叉树后序遍历
- Binary Tree Postorder Traversal Java
- LeetCode 题解(86): Binary Tree Postorder Traversal
- LeetCode题解:Binary Tree Postorder Traversal
- LeetCode题解-145-Binary Tree Postorder Traversal
- 模仿大众点评过滤框
- CvMemStorage
- DrawerLayout Demo
- 欢迎使用CSDN-markdown编辑器
- iOS GCD使用
- LeetCode145 Binary Tree Postorder Traversal Java题解(递归 迭代)
- [TOOLS] SVN命令使用详解
- Kind Editor 编辑器 图片上传
- 灵犀云智能语音能力【火力全开】
- 重写、覆盖、重载、隐藏、多态几个概念的区别分析
- 整数划分定义与解析(递归)
- H.264难点问题分析
- Java Web中的入侵检测及简单实现
- TCP_TW_REUSE设置