leetcode 144. Binary Tree Preorder Traversal
2016-05-23 11:44
323 查看
题目内容
Given a binary tree, return the preorder traversal of its nodes’ values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,2,3].
Note: Recursive solution is trivial, could you do it iteratively?
题目分析
二叉树的先序遍历。从根结点开始遍历,一直遍历到“最左的子结点”,然后访问该分支下的右结点。
本题不让用递归调用,用迭代来解决。
Given a binary tree, return the preorder traversal of its nodes’ values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,2,3].
Note: Recursive solution is trivial, could you do it iteratively?
题目分析
二叉树的先序遍历。从根结点开始遍历,一直遍历到“最左的子结点”,然后访问该分支下的右结点。
本题不让用递归调用,用迭代来解决。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> ans=new LinkedList<Integer>(); Stack<TreeNode> stack= new Stack<TreeNode>(); if(root!=null) stack.push(root); while(!stack.isEmpty()) { TreeNode node=stack.pop(); ans.add(node.val); if(node.right!=null) stack.push(node.right); if(node.left!=null) stack.push(node.left); } return ans; } }
相关文章推荐
- 设计模式中需要用到的原则
- 《Android开发艺术》之View的事件体系(上)
- [spring源码学习]十、IOC源码-conversionService
- C/C++中的拷贝构造函数和赋值构造函数
- 第10课:Spark Streaming源码解读之流数据不断接收全生命周期彻底研究和思考
- 在Dropbox上搭建私有的Git仓库的教程
- 第十三周阅读程序(1)
- JavaScript基本语法
- 字符串fprint format参数详解
- 你需要知道的Android拍照适配方案
- 入职实习第四天:ViewTreeObserver简介
- Android动画-概述
- 【Leetcode】之Minimum Path Sum
- 为何总是拿到薪资范围下限的offer?
- 网站 、内容
- matlab中的数字滤波器
- 2016最新经典爆笑职场笑话
- Smarty实现页面静态化(生成HTML)的方法
- oracle 序列
- 那些年我们经历过的职场笑话