Java [Leetcode 144]Binary Tree Preorder Traversal

题目描述:

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].

解题思路:文章来源地址:https://www.yii666.com/article/756108.html

这个问题最简单的方法是使用递归,但是题目规定不能使用,得使用迭代的方法。网址:yii666.com

那么我们考虑使用栈来实现。文章地址https://www.yii666.com/article/756108.html网址:yii666.com<

思路是每次遍历这节点,把该点的值放入list中,然后把该点的右孩子放入栈中,并将当前点设置为左孩子,然后迭代的去访问当前点;如果遇到当前点的左孩子为空,则弹出栈中的点(如果栈不为空的情况下),然后继续迭代。

代码如下:

/**
* 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> res = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode node = root;
while(node != null){
res.add(node.val);
if(node.right != null)
stack.push(node.right);
node = node.left;
if(node == null && !stack.isEmpty())
node = stack.pop();
}
return res;
}
}

  文章来源地址https://www.yii666.com/article/756108.html

版权声明:本文内容来源于网络,版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。文本页已经标记具体来源原文地址,请点击原文查看来源网址,站内文章以及资源内容站长不承诺其正确性,如侵犯了您的权益,请联系站长如有侵权请联系站长,将立刻删除

Java [Leetcode 144]Binary Tree Preorder Traversal-相关文章

  1. Java [Leetcode 94]Binary Tree Inorder Traversal

  2. Java [Leetcode 144]Binary Tree Preorder Traversal

  3. Java [Leetcode 257]Binary Tree Paths

  4. Java [Leetcode 102]Binary Tree Level Order Traversal

  5. Java [Leetcode 107]Binary Tree Level Order Traversal II

  6. LeetCode第[98]题(Java):Validate Binary Search Tree(验证二叉搜索树)

  7. A multi-faceted language for the Java platform

    最近在研究关于groovy 相关的技术 希望有研究交到研究这方面的朋友Groovy 最新的地址http://www.groovy-lang.org/

  8. java 集合 Se HashTreeSet

    Set接口 Set是Collection的子接口,与List相对 Set集合中的元素的特点是1,无序性 2,无下标3,无重复的元素 Set是个接口,所以无法直接创建对象,要依赖它的实现类来创建对象 Set的实现类有两个,一个是HashSet,另一个是TreeSet输出的结果是Set的成员方法基本上都是继承了collection方法 下

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信图片_20190322181744_03.jpg

微信扫一扫打赏

请作者喝杯咖啡吧~

支付宝扫一扫领取红包,优惠每天领

二维码1

zhifubaohongbao.png

二维码2

zhifubaohongbao2.png