lintcode,二叉树的前序遍历
来源:互联网 发布:初中生 18cm 知乎 编辑:程序博客网 时间:2024/04/30 13:12
给出一棵二叉树,返回其节点值的前序遍历。
解题思路:递归和非递归,三种遍历类似。
一刷ac
递归
/** * 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) { ArrayList<Integer> res = new ArrayList<Integer>(); if(root == null) return res; res.add(root.val); if(root.left != null) res.addAll(preorderTraversal(root.left)); if(root.right != null) res.addAll(preorderTraversal(root.right)); return res; }}
非递归
/** * 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) { ArrayList<Integer> res = new ArrayList<Integer>(); if(root == null) return res; Stack<TreeNode> stack = new Stack<TreeNode>(); stack.push(root); while(!stack.empty()){ TreeNode node = stack.pop(); res.add(node.val); if(node.right != null) stack.push(node.right); if(node.left != null) stack.push(node.left); } return res; }}
0 0
- LintCode -- 二叉树的前序遍历
- lintcode 二叉树的前序遍历
- lintcode,二叉树的前序遍历
- LintCode-二叉树的前序遍历
- lintcode 二叉树的前序遍历
- LintCode 二叉树的前序遍历
- lintcode二叉树的前序遍历
- 二叉树的前序遍历-LintCode
- Lintcode 二叉树的前序遍历
- lintcode--二叉树的前序遍历
- lintcode:二叉树的前序遍历
- lintcode-二叉树的前序遍历(非递归)-66
- LintCode之二叉树的前序遍历
- Lintcode 66 二叉树的前序遍历
- LintCode | 66. 二叉树的前序遍历
- lintcode——二叉树的前序遍历
- lintcode 66 二叉树的前序遍历
- LintCode 66 二叉树的前序遍历
- Leetcode 之 Remove Nth Node From End of List
- 第十六周 算法验证快速排序
- 安卓模拟器-Genymotion
- [课堂笔记]在VMware Workstation上安装linux系统的高级操作(自定义)--有界面安装
- Glide使用
- lintcode,二叉树的前序遍历
- Hibernate懒加载导致json数据对象传输异常的问题---(非常重要)
- java Enumeration接口的使用例子
- sublime text3实用教程-安装js智能提示插件
- java汇编代码学习(一)基本类型与数组类型
- express-session
- Java中重载与重写的区别
- Java连接数据库第一版
- python-xgboost调参经验