【LeetCode】Binary Tree Preorder Traversal
来源:互联网 发布:旅行社推荐知乎 编辑:程序博客网 时间:2024/05/17 02:18
题目
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 binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } *///1.递归public class Solution { public ArrayList<Integer> preorderTraversal(TreeNode root) { ArrayList<Integer> result=new ArrayList<Integer>(); preorder(root,result); return result; } public void preorder(TreeNode root,ArrayList<Integer> result){ if(root!=null){ result.add(root.val); preorder(root.left,result); preorder(root.right,result); } }}//2.非递归public class Solution { public ArrayList<Integer> preorderTraversal(TreeNode root) { ArrayList<Integer> result=new ArrayList<Integer>(); if(root==null) return result; Stack<TreeNode> stack=new Stack<TreeNode>(); stack.push(root); while(!stack.empty()){ TreeNode tn=stack.pop(); result.add(tn.val); if(tn.right!=null){ stack.push(tn.right); } if(tn.left!=null){ stack.push(tn.left); } } return result; }}
---EOF---
0 0
- LeetCode Binary Tree Preorder Traversal
- 【LeetCode】Binary Tree Preorder Traversal
- Leetcode: Binary Tree Preorder Traversal
- Leetcode Binary Tree Preorder Traversal
- LeetCode:Binary Tree Preorder Traversal
- Leetcode: Binary Tree Preorder Traversal
- LeetCode:Binary Tree Preorder Traversal
- [LeetCode]Binary Tree Preorder Traversal
- [LeetCode] Binary Tree Preorder Traversal
- LeetCode | Binary Tree Preorder Traversal
- Leetcode: Binary Tree Preorder Traversal
- [LeetCode] Binary Tree Preorder Traversal
- LeetCode - Binary Tree Preorder Traversal
- LeetCode - Binary Tree Preorder Traversal
- 【LeetCode】Binary Tree Preorder Traversal
- [LeetCode]Binary Tree Preorder Traversal
- Binary Tree Preorder Traversal - LeetCode
- [Leetcode] Binary Tree Preorder Traversal
- CSS实现Table没有外边框,只有内边框
- POJ 2468 Apple Tree 树上瞎搞分组背包
- Android自动测试之Monkey工具
- STL SET 常用操作简介[转载]
- 在Eclipse中编辑Hadoop2.2.0源代码
- 【LeetCode】Binary Tree Preorder Traversal
- Oracle8的不安全因素及几点说明
- strcmp 安全问题
- 有没有带过孩子的家长们可以进来解惑一下,为什么中国孩子不穿纸尿裤?
- ssh中“Host key verification failed.“的解决方案
- Maven笔记10-Maven生成项目站点
- Android - 文件读写操作 总结
- 学习札记——JSP实现登陆后返回历史浏览页面
- Oracel Synonym 跨实例访问表