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?
private Stack<TreeNode> stack = new Stack<TreeNode>(); public ArrayList<Integer> preorderTraversal(TreeNode root) { ArrayList<Integer> al = new ArrayList<Integer>(); if (root != null) { stack.push(root); while (stack.size() != 0) { TreeNode node = stack.pop();; al.add(node.val); if (node.right != null) { stack.push(node.right); } if (node.left != null) { stack.push(node.left); } } } return al; }
Binary Tree Preorder Traversal,布布扣,bubuko.com
Binary Tree Preorder Traversal
原文地址:http://blog.csdn.net/u010378705/article/details/36026935