题目 :给你二叉树的根节点 root
,返回它节点值的 前序 遍历。
思路:根 左 右
代码:
java
/**
* 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) {
List<Integer> res = new ArrayList<>();
dfs(res, root);
return res;
}
private void dfs(List<Integer> res, TreeNode root) {
if (root == null)
return;
res.add(root.val);
dfs(res, root.left);
dfs(res, root.right);
}
}
性能:
时间复杂度o(n)
空间复杂度o(n)