首页 > 代码库 > Binary Tree Preorder Traversal leetcode java
Binary Tree Preorder Traversal leetcode java
题目:
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?
题解:
递归做法如下:
1 public void helper(TreeNode root, ArrayList<Integer> re){
2 if(root==null)
3 return;
4 re.add(root.val);
5 helper(root.left,re);
6 helper(root.right,re);
7 }
8 public ArrayList<Integer> preorderTraversal(TreeNode root) {
9 ArrayList<Integer> re = new ArrayList<Integer>();
10 if(root==null)
11 return re;
12 helper(root,re);
13 return re;
14 }
2 if(root==null)
3 return;
4 re.add(root.val);
5 helper(root.left,re);
6 helper(root.right,re);
7 }
8 public ArrayList<Integer> preorderTraversal(TreeNode root) {
9 ArrayList<Integer> re = new ArrayList<Integer>();
10 if(root==null)
11 return re;
12 helper(root,re);
13 return re;
14 }
非递归方法:
1 public ArrayList<Integer> preorderTraversal(TreeNode root) {
2 ArrayList<Integer> res = new ArrayList<Integer>();
3 if(root == null)
4 return res;
5 LinkedList<TreeNode> stack = new LinkedList<TreeNode>();
6 while(root!=null || !stack.isEmpty()){
7 if(root!=null){
8 stack.push(root);
9 res.add(root.val);
10 root = root.left;
11 }
12 else{
13 root = stack.pop();
14 root = root.right;
15 }
16 }
17 return res;
18 }
2 ArrayList<Integer> res = new ArrayList<Integer>();
3 if(root == null)
4 return res;
5 LinkedList<TreeNode> stack = new LinkedList<TreeNode>();
6 while(root!=null || !stack.isEmpty()){
7 if(root!=null){
8 stack.push(root);
9 res.add(root.val);
10 root = root.left;
11 }
12 else{
13 root = stack.pop();
14 root = root.right;
15 }
16 }
17 return res;
18 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。