Binary Tree Preorder Traversal
来源:互联网 发布:管家婆erp软件 编辑:程序博客网 时间:2024/05/22 17:47
题目:Given a binary tree, return the preorder traversal of its nodes' values.
Note: Recursive solution is trivial, could you do it iteratively?
非递归先序遍历一棵二叉树
之前遇到都是写的递归式的,觉得迭代方式不好理解,然后在discuss里看到一句解释 Just remember to push the right child and then the left child, which makes the left one come out first. 觉得就好理解的多了
public List<Integer> preorderTraversal(TreeNode root) { List<Integer> list = new ArrayList<Integer>(); if (root == null) { return list; } Stack<TreeNode> stack = new Stack<TreeNode>(); stack.push(root); while (!stack.isEmpty()) { TreeNode node = stack.pop(); list.add(node.val); if (node.right != null) { stack.push(node.right); } if (node.left != null) { stack.push(node.left); } } return list;}
0 0
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal
- 异步内存、直接复制及流处理复制对比
- excel向程序发送命令时出现问题
- unity小项目主角打击怪物
- 这是第一篇的标题
- DIV+CSS入门案例
- Binary Tree Preorder Traversal
- mahout(或者hadoop)优先使用用户指定的classpath加载jar包
- iOS摘
- 渐进式下溢出
- JAVA菜鸟入门篇 - Java重载 (十二)
- 《现代操作系统4th》英文版阅读笔记 4.3章 文件系统实现
- 红黑树学习下篇
- set方法
- 【Java.Spring.Core】【IoC】Beans