/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
if (root == null) {
return new ArrayList<>();
}
List<Integer> list = new ArrayList<>();
pre(root, list);
return list;
}
public void pre(TreeNode head, List<Integer> res) {
if (head == null) {
return;
}
res.add(head.val);
pre(head.left, res);
pre(head.right, res);
}
}
LeetCode-144:二叉树的前序遍历(Java语言实现)
最新推荐文章于 2024-08-17 22:06:38 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)