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?
Subscribe to see which companies asked this question
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<Integer>();
if(root != null){
preorder(root,list);
}
return list;
}
private void preorder(TreeNode root,List<Integer> list){
list.add(root.val);
if(root.left!=null){
preorder(root.left,list);
}
if(root.right!=null){
preorder(root.right,list);
}
}
}
本文介绍了一种实现二叉树前序遍历的方法,通过递归方式获取树节点的值并返回遍历结果。示例代码展示了如何对特定二叉树进行前序遍历。
1192

被折叠的 条评论
为什么被折叠?



