Given a binary tree, return the preorder traversal of its nodes' values.
来源:互联网 发布:网络连环夺宝 编辑:程序博客网 时间:2024/05/17 09:32
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?
java实现:
方法一:
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */import java.util.ArrayList;public class Solution { ArrayList<Integer> out =new ArrayList<Integer>(); public ArrayList<Integer> preorderTraversal(TreeNode root) { if(root==null){ return out; } out.add(root.val); if(root.left!=null){ preorderTraversal(root.left); } if(root.right!=null){ preorderTraversal(root.right); } return out; }}
方法二:
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */import java.util.ArrayList;import java.util.Stack;public class Solution { public ArrayList<Integer> preorderTraversal(TreeNode root) { ArrayList<Integer> out=new ArrayList<Integer>(); Stack<TreeNode> q=new Stack<TreeNode>(); if(root==null){ return out; } q.push(root); while(!q.isEmpty()){ TreeNode temp=q.pop(); if(temp.right!=null){ q.push(temp.right); } if(temp.left!=null){ q.push(temp.left); } out.add(temp.val); } return out; }}
0 0
- Given a binary tree, return the preorder traversal of its nodes' values.
- Given a binary tree, return the preorder traversal of its nodes' values.
- Given a binary tree, return the postorder traversal of its nodes' values.
- LeetCode Given a binary tree, return the postorder traversal of its nodes' values.
- Given preorder and inorder traversal of a tree, construct the binary tree.
- 4 4 Given a binary search tree, design an algorithm which creates a linked list of all the nodes at
- LeetCode 之 preorder traversal of binary tree
- CareerCup Given preorder traversal array of a BST, recontruct the BST.
- Construct a special tree from given 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
- Unity高自由度轨道旋转
- react-native 完整实现登录功能
- tableview实现单个cell的展开和收起
- lianbiao
- Win10 清空回收站
- Given a binary tree, return the preorder traversal of its nodes' values.
- 以ssm+mvc框架来开发一个系统的基本流程
- .NET-File, XmlDocument, WebService读写文件APIs总结
- Android 开发框架 MVVM 小试
- mencoder.exe在win10下将y4m转换成yuv文件
- Codeforces 697C Lorenzo Von Matterhorn 题解
- 狂涨结束:内存和固态硬盘终于要降价了
- hdu 2086 A1 = ?(递推)
- c/c++调用libcurl库发送http请求