class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
if (root == null) return list;
dfs(root, list);
return list;
}
public void dfs(TreeNode node, List<Integer> ans) {
ans.add(node.val);
if (node.left != null) dfs(node.left, ans);
if (node.right != null) dfs(node.right, ans);
}
}
原文地址:https://www.cnblogs.com/acbingo/p/9439927.html
时间: 2024-10-08 12:05:59