二叉树之路径系列
节点定义
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;
}
@Override
public String toString() {
return String.valueOf(this.val);
}
}
根节点到所有叶子节点的路径
public static void main(String[] args){
TreeNode root=new TreeNode(1);
List<String>paths=new ArrayList<>();
getPath(root,paths,root.val+"");
}
//记录根节点到叶子结点的所有路径
public static void getPath(TreeNode node, List<String> paths,String s){
if(node.left==null&&node.right==null){ //叶子结点
paths.add(s);
return;
}
if(node.left!=null){
getPath(node.left, paths, s);
}
if(node.right!=null){
getPath(node.right, paths, s);
}
}
根节点到指定节点的路径
//寻找根节点到某一特定子节点路径
public static boolean getPathToNode(TreeNode node, List<Integer> path, int target) {
path.add(node.val);
if (node.val == target) return true;
boolean flag = false;
if (node.left != null) {
flag = getPathToNode(node.left, path, target);
}
if (!flag&&node.right != null) {
flag = getPathToNode(node.right, path, target);
}
//当前节点及其子树 都未找到target 需要在返回父节点之前,在路径上删除当前节点(回溯)
if (!flag) path.remove(path.size() - 1);
return flag;
}
参考链接:
https://blog.csdn.net/liuyi1207164339/article/details/50908308