您的位置:首页 > 其它

Leetcode_144_Binary Tree Preorder Traversal

2015-01-19 18:37 417 查看
本文是在学习中的总结,欢迎转载但请注明出处: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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: