二叉树遍历
来源:互联网 发布:js验证用户名是否存在 编辑:程序博客网 时间:2024/06/05 21:59
前序遍历:非递归解法
public class Solution { /** * @param root: The root of binary tree. * @return: Preorder in ArrayList which contains node values. */ public ArrayList<Integer> preorderTraversal(TreeNode root) { // write your code here ArrayList<Integer> result = new ArrayList<Integer>(); Stack<TreeNode> stack = new Stack<TreeNode>(); if(root == null){ return result; } stack.push(root); while(!stack.empty()){ TreeNode temp = stack.pop(); result.add(temp.val); if(temp.right!=null){ stack.push(temp.right); } if(temp.left!=null){ stack.push(temp.left); } } return result; }}
中序遍历:非递归解法
public class Solution { /** * @param root: The root of binary tree. * @return: Inorder in ArrayList which contains node values. */ public ArrayList<Integer> inorderTraversal(TreeNode root) { // write your code here ArrayList<Integer> result = new ArrayList<Integer>(); Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode cur = root; while(cur != null || !stack.empty()){ while(cur != null){ stack.push(cur); cur = cur.left; } cur = stack.peek(); result.add(cur.val); stack.pop(); cur = cur.right; } return result; }}
后续遍历:递归解法
public class Solution { /** * @param root: The root of binary tree. * @return: Postorder in ArrayList which contains node values. */ public ArrayList<Integer> postorderTraversal(TreeNode root) { // write your code here ArrayList<Integer> result = new ArrayList<Integer>(); if(root == null){ return result; } result.addAll(postorderTraversal(root.left)); result.addAll(postorderTraversal(root.right)); result.add(root.val); return result; }}
0 0
- 二叉树遍历、分层遍历
- 遍历二叉树--二叉树
- 【树】遍历二叉树
- 二叉树遍历
- 二叉树遍历
- 二叉树的遍历
- (原创)遍历二叉树
- 二叉树遍历-php
- 查找--遍历二叉树
- 遍历二叉树
- 二叉树遍历规则
- 二叉树的遍历
- 二叉树遍历
- 遍历二叉树
- 二叉树遍历问题
- 二叉树遍历
- 二叉树遍历(zz)
- 二叉树的遍历
- Notepad++配合QuickText打造快速高效的文本编辑器
- 深入理解Java:注解(Annotation)--注解处理器
- 【Python】Learn Python the hard way, ex2 注释
- Matlab GUI设计——文件读取和保存uigetfile,uiputfile
- hdu5073 Galaxy(暴力)
- 二叉树遍历
- 使用insert和select选项,可以把数据从一张表复制到另外一张表
- swif通过代码生成子视图
- c apache2模块开发--根据自定义业务逻辑实现文件下载
- uva 1636 概率
- access 删除字段为空的值
- hdu2079选课时间(动态规划&&母函数)
- tarjan算法入门整理专题(判断是否是一个强连通、通过缩点求至少加几条边让整个图变成强连通和传递的最小费用)
- 代码实现Lable 、textField创建界面以及键盘的处理