Binary Tree Preorder Traversal
Total Accepted: 67121 Total Submissions: 185051My Submissions
Question Solution
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]
.
分析:先序遍历树中的节点,采用递归的方法
public class Solution {
List<Integer> x=new ArrayList<Integer>();
void preTra(TreeNode r) {
if(r!=null)
{
x.add(r.val);
preTra(r.left);
preTra(r.right);
}
}
public List<Integer> preorderTraversal(TreeNode root) {
preTra(root);
return x;
}
}
时间: 2024-10-13 03:04:48