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?
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private ArrayList<Integer> result = new ArrayList<Integer>();
public ArrayList<Integer> preorder(TreeNode root){
if(root == null)
return result;
else {
result.add(root.val);
preorder(root.left);
preorder(root.right);
return result;
}
}
public ArrayList<Integer> preorderTraversal(TreeNode root) {
preorder(root);
return result;
}
}
本文介绍了一种实现二叉树前序遍历的方法,包括递归算法的具体实现细节。通过对二叉树节点的访问顺序进行定义,该文提供了一个清晰的解决方案,并附带了完整的Java代码示例。
1127

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



