本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/42876699
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)题意为前序遍历二叉树。遍历顺序为根—>左—>右。
(2)考虑到用递归比较简单,本文使用递归的思想进行解决,由于比较简单这里不累赘,详见下方代码。
(3)希望本文对你有所帮助。
算法代码实现如下:
/** * @author liqq */ public List<Integer> preorderTraversal(TreeNode root) { List<Integer> result = new LinkedList<Integer>(); if (root != null) { result.add(root.val); pre_order(result, root.left); pre_order(result, root.right); } return result; } private void pre_order(List<Integer> result, TreeNode curr) { if (curr != null) { result.add(curr.val); pre_order(result, curr.left); pre_order(result, curr.right); } }