1. traversal thought (root around)
Note: 1 each time the list will be empty;.
2. The need to record the location on the back)
class Solution {
List<Integer> list=new ArrayList<>();
private void preorder(TreeNode root){
if(root!=null){
list.add(root.val);
preorder(root.left);
preorder(root.right);
}
}
public List<Integer> preorderTraversal(TreeNode root) {
list.clear();//清空
preorder(root);
return list;
}
}
2. Summary of thought (the first one by traversing the left subtree, and then traverse the right subtree, during the last summary)
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
if(root==null)
{
return new ArrayList<>();//当root为空时,返回一个空链表
}
List<Integer> left=preorderTraversal(root.left);//求出所有左子树节点
List<Integer> right=preorderTraversal(root.right);//求出右子树结点
List<Integer> list=new ArrayList<>();
list.add(root.val);
list.addAll(left);//将链表节点全部进行尾插到新链表中
list.addAll(right);
return list;
}
}