Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree
Given binary tree
{1,#,2,3}, 1
\
2
/
3
return
[1,2,3].
Analysis:
Use stack to temporarily store the nodes. Because stack is FILO, push order is from right to left. I spent about half an hour thinking the idea. It was my first time implement the preorder traversal.
Solution:
1: /**
2: * Definition for binary tree
3: * public class TreeNode {
4: * int val;
5: * TreeNode left;
6: * TreeNode right;
7: * TreeNode(int x) { val = x; }
8: * }
9: */
10: public class Solution {
11: public ArrayList preorderTraversal(TreeNode root) {
12: ArrayList result = new ArrayList();
13: if(root==null)
14: return result;
15: Stack<TreeNode> nodeStack=new Stack<TreeNode>();
16: nodeStack.push(root);
17: while(!nodeStack.isEmpty())
18: {
19: TreeNode current=nodeStack.pop();
20: if(current.right!=null) nodeStack.push(current.right);
21: if(current.left!=null) nodeStack.push(current.left);
22: result.add(current.val);
23: }
24: return result;
25: }
26: }
没有评论:
发表评论