NC8题解 | #二叉树中和为某一值的路径(二)#

二叉树中和为某一值的路径(二)

http://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca

dfs递归解法

  1. 全局变量 ArrayList<ArrayList<>> ll保存所有路径
  2. 递归调用方法
  3. 传参:
  • 上一级传递过来的root根节点
  • 上一级传递过来的路径
  • 上一级传递过来的数值

错误解法

错误解法:比较数值,小于期望值的就中断
错误原因:未考虑负数情况

public class Solution {
    ArrayList<ArrayList<Integer>> ll = new ArrayList<ArrayList<Integer>>();
    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int expectNumber) {
        ArrayList<Integer> path = new ArrayList();
        rec(root,path,expectNumber);
        return ll;
    }
    public void rec(TreeNode root, ArrayList<Integer> path, int expectNumber){
        if(root == null){
            return;
        }
        ArrayList<Integer> newPath = new ArrayList(path);
        if(expectNumber < root.val){
            return;
        }else if(expectNumber == root.val){
            newPath.add(expectNumber);
            if(root.left == null && root.right == null){
                ll.add(newPath);
            }
        }else{
            newPath.add(root.val);
            int n = expectNumber - root.val;
            rec(root.left,newPath,n);
            rec(root.right,newPath,n);
        }
    }
    
}

正确解法

1、先判断是否叶子节点
2、判断是否等于预期值

import java.util.*;
public class Solution {
     ArrayList<ArrayList<Integer>> ll = new ArrayList<ArrayList<Integer>>();
    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int expectNumber) {
        ArrayList<Integer> path = new ArrayList();
        rec(root,path,expectNumber);
        return ll;
    }
    public void rec(TreeNode root, ArrayList<Integer> path, int expectNumber){
        if(root == null){
            return;
        }
        ArrayList<Integer> newPath = new ArrayList(path);
        newPath.add(root.val);
        if(root.left != null){
            rec(root.left, newPath, expectNumber - root.val);
        }
        if(root.right != null){
            rec(root.right, newPath, expectNumber - root.val);
        }
        if(root.left == null && root.right == null){
            if(root.val == expectNumber){
                ll.add(newPath);
            }
        }
    }
    
}
全部评论

相关推荐

不知道怎么取名字_:两个方向 1.简历针对性准备下 2.面试前也需要准备的 主要还是要看各个公司需求,看公司行业和岗位描述,那里面已经写了对技术的需求,一份简历,不可能和所有嵌入式岗位都匹配的
投递北京经纬恒润科技股份有限公司等公司6个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务