Lintcode 二叉树前序遍历
来源:互联网 发布:ios开源项目源码 编辑:程序博客网 时间:2024/05/10 13:10
二叉树前序遍历
给出一棵二叉树,返回其节点值的前序遍历。
样例
给出一棵二叉树 {1,#,2,3}
,
1 \ 2 / 3
返回 [1,2,3]
.
二叉树的前序遍历:根节点->左子树->右子树。下图的前序遍历结果为:abdefgc。
通过递归方式实现前序遍历的代码如下:
/** * 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: The root of binary tree. * @return: Preorder in ArrayList which contains node values. */ ArrayList<Integer> list = new ArrayList<Integer>(); public ArrayList<Integer> preorderTraversal(TreeNode root) { // write your code here preorder(root); return list; } private void preorder(TreeNode root){ if(root == null) return; list.add(root.val); preorder(root.left); preorder(root.right); }}
通过非递归方式实现前序遍历的代码如下:
/** * 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: The root of binary tree. * @return: Preorder in ArrayList which contains node values. */ public ArrayList<Integer> preorderTraversal(TreeNode root) { // write your code here Stack<TreeNode> stack = new Stack<TreeNode>(); ArrayList<Integer> list = new ArrayList<Integer>(); while(root!=null||stack.size()>0){ while(root!=null){ list.add(root.val); stack.push(root); root = root.left; } if(stack.size()>0){ root = stack.pop(); root = root.right; } } return list; }}
0 0
- Lintcode 二叉树前序遍历
- Lintcode 二叉树中序遍历
- 二叉树中序遍历-lintcode
- 二叉树层次遍历-LintCode
- lintcode.68 二叉树后序遍历
- LintCode-二叉树的层次遍历 II
- LintCode 二叉树的层次遍历
- LintCode 二叉树的层次遍历 II
- lintcode-二叉树的层次遍历-69
- LintCode -- 二叉树的前序遍历
- LintCode -- 二叉树的中序遍历
- LintCode -- 二叉树的后序遍历
- Lintcode 二叉树的后序遍历
- lintcode 二叉树的中序遍历
- lintcode 二叉树的前序遍历
- LintCode:二叉树的后序遍历
- Lintcode 二叉树后序遍历 非递归形式
- LintCode:二叉树的层次遍历
- 剑指offer—求1+2+3+...+n
- Android混淆打包后openFileChooser无法使用找不到的解决方法
- hdoj Work 5326 (并查集+技巧) 好题
- UIWebView和WKWebView 改变HTML 图片尺寸 及 字体大小
- C#中的特定类型数组的默认值
- Lintcode 二叉树前序遍历
- Merge Two Sorted List
- ORACLE笔记
- C__函数中的静态变量_static
- 匿名内部类和内部类
- XSS跨站脚本攻击剖析与防御
- 在两个activity之间传送数据
- Codeforces Round #324 (Div. 2)——C. Marina and Vasya
- 剑指offer—把字符串转换成整数