LeetCode 之 preorder traversal of binary tree
来源:互联网 发布:模拟人生4邪恶补丁mac 编辑:程序博客网 时间:2024/05/16 01:40
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?
两种解法, 一种是递归 一种是迭代
线上节点类:
package node;public class TreeNode {private int val;private TreeNode left;private TreeNode right;public TreeNode(int x) {val = x;}public int getVal(){return this.val;}public void setVal(int val){this.val = val;}public TreeNode getLeft(){return this.left;}public TreeNode getRight(){return this.right;}public void setLeft(TreeNode left){this.left = left;}public void setRight(TreeNode right){this.right = right;}}
(1) 递归
public ArrayList<Integer> preorderTraversal(TreeNode root) {ArrayList<Integer> result = new ArrayList<Integer>();if (root != null) {result.addAll(preorderTraversal(root.getLeft()));result.add(root.getVal());result.addAll(preorderTraversal(root.getRight()));}return result; }(2)迭代
迭代使用stack 来实现,先进后出。
public ArrayList<Integer> preOrder(TreeNode root){ ArrayList<Integer> result = new ArrayList<Integer>(); Stack<TreeNode> nodeStack = new Stack<TreeNode>(); nodeStack.push(root); while(!nodeStack.isEmpty()){ TreeNode node = nodeStack.pop(); result.add(node.getVal()); if(node.getRight()!=null){ nodeStack.push(node.getRight()); } if(node.getLeft()!=null){ nodeStack.push(node.getLeft()); } } return result; }
0 0
- LeetCode 之 preorder traversal of binary tree
- 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
- Leetcode: Binary Tree Preorder Traversal
- 关于myeclipse或者eclipse中导出jar包
- 软件滤波,硬件滤波
- Unity3d的2D骨骼动画插件Puppet2D的 基础训练2
- LeetCode 之 Remove Nth Node From End of List
- air max femme pas cher he eventually transferred to the School of Journalism Department radio and te
- LeetCode 之 preorder traversal of binary tree
- 记账
- 怕品炕桥孪值绿讶屎淳母栽仆潘怪
- JAVA菜鸟入门篇-JAVA发展历史
- mac sublime text 2 怎样修改字体?
- scala 简要: Actor
- 32位汇编语言学习笔记(28)--一个简单的光标控制程序
- 西门子变频器参数设置【转】
- 新浪微博数据挖掘食谱之七: 查询篇 (查询最流行的微博)