113、路径总和 II
给你二叉树的根节点 root
和一个整数目标和 targetSum
,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。
回溯算法和二叉树的结合
class Solution {
List<List<Integer>>res=new ArrayList<>();
List<Integer>list=new ArrayList<>();
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
preOrder(root,targetSum);
return res;
}
public void preOrder(TreeNode root,int targetSum){
if(root==null) return ;
list.add(root.val);
targetSum-=root.val;
if(root.left==null&&root.right==null&&targetSum==0){
res.add(new ArrayList<>(list));
}
preOrder(root.left,targetSum);
preOrder(root.right,targetSum);
list.remove(list.size()-1);//回溯的标志
}
}
429、N 叉树的层序遍历
给定一个 N 叉树,返回其节点值的层序遍历。(即从左到右,逐层遍历)。
层序遍历就用队列解决
class Solution {
public List<List<Integer>> levelOrder(Node root) {
List<List<Integer>>res=new ArrayList<>();
Queue<Node>queue=new LinkedList<>();
if(root==null) return res;
queue.offer(root);
while(!queue.isEmpty()){
int size=queue.size();
List<Integer>list=new ArrayList<>();
while(size>0){
Node temp=queue.poll();
list.add(temp.val);
for(Node child:temp.children){
queue.offer(child);
}
size--;
}
res.add(list);
}
return res;
}
}
590、N 叉树的后序遍历
给定一个 n 叉树的根节点 root
,返回 其节点值的 后序遍历 。
class Solution {
public List<Integer> postorder(Node root) {
List<Integer>list=new ArrayList<>();
if(root==null) return list;
post(root,list);
return list;
}
public void post(Node root,List<Integer>list){
if(root==null) return ;
for(Node child:root.children){
post(child,list);
}
list.add(root.val);
}
}