LeetCode 144. Binary Tree Preorder Traversal 解题报告
Posted bruce128
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 144. Binary Tree Preorder Traversal 解题报告相关的知识,希望对你有一定的参考价值。
Total Accepted: 108336 Total
Submissions: 278322 Difficulty: Medium
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?
Subscribe to see which companies asked this question
Show Similar Problems
Have you met this question in a real interview?
Yes
No
求一棵二叉树的先根遍历序。题目说了,递归的解法十分简单,能否用非递归的方式求解。
每遍历一个节点的时候,将右孩子入栈。向左搜索直到为空时,弹栈。
我的AC代码
public class BinaryTreePreorderTraversal { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> list = new ArrayList<Integer>(); Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode cur = root; while (cur != null || !stack.isEmpty()) { while (cur != null) { list.add(cur.val); if(cur.right != null) stack.add(cur.right); cur = cur.left; } if(!stack.isEmpty()) cur = stack.pop(); } return list; } }
以上是关于LeetCode 144. Binary Tree Preorder Traversal 解题报告的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 144. Binary Tree Preorder Traversal
[leetcode-144-Binary Tree Preorder Traversal]
LeetCode-144-Binary Tree Preorder Traversal
leetcode [144]Binary Tree Preorder Traversal