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; } * } */
//先序遍历:root->left->right public class Solution { public List<Integer> preorderTraversal(ArrayList<Integer> list,TreeNode root){ //重写方法,多态 if(root==null) return list; list.add(root.val); //在内部不能新建List,所有递归遍历结果都写到同一个list if(root.left!=null) preorderTraversal(list,root.left); //注意此处递归调用时的参数list和外围的list是同一个 if(root.right!=null) preorderTraversal(list,root.right); return list; } public List<Integer> preorderTraversal(TreeNode root) { ArrayList<Integer> result = new ArrayList<Integer>(); //List是继承自Collection的接口,而ArrayList和LinkedList才是类 if(root==null) return result; result.add(root.val); if(root.left!=null) preorderTraversal(result,root.left); //注意:此处多态调用保证将遍历结果写到result中,如直接调用 if(root.right!=null) preorderTraversal(result,root.right);//preorderTraversal(root.left),则在调用的内部会新建一个result //而不是将遍历结果写到外围的result中,导致result只有一个值root.val return result; //此处隐含了一个向上转型 } }
//利用栈,迭代写法,思想参考中序遍历的博客,只是while循环中重新压入栈的顺序不同 public class Solution { public List<Integer> preorderTraversal(TreeNode root) { ArrayList<Integer> result = new ArrayList<Integer>(); if(root==null) return result; Stack<TreeNode> nodeStack = new Stack<TreeNode>(); Stack<Integer> countStack = new Stack<Integer>(); nodeStack.push(root); countStack.push(0); while(!nodeStack.empty()){ TreeNode node = nodeStack.pop(); int count = countStack.pop(); if(count==1){ result.add(node.val); }else{ if(node.right!=null){ nodeStack.push(node.right); countStack.push(0); } if(node.left!=null){ nodeStack.push(node.left); countStack.push(0); } nodeStack.push(node); countStack.push(1); } } return result; } }