1、二叉树的每一个叶子节点,其实都不是最终的终止节点,下面会有两个为空的叶子节点,它们才是最终的节点

   如果不注意这个,可能会引起一些相应的问题:

   下面的题目是剑指offer : https://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca?tpId=13&tqId=11177&tPage=2&rp=2&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

import java.util.*;
public class Solution {
    private static ArrayList<ArrayList<Integer>> result = new ArrayList();
    public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int target) {
        // 鲁棒性
        if(root == null)
            return result;
        
        ArrayList<Integer> arr = new ArrayList();
        getPath(root, arr, target);
        return result;
    }
    
    
    public static void getPath(TreeNode root, ArrayList arr, int target){
        // 先判断
        if(root == null ){
             if(target == 0){
                result.add(arr);
             }
          return ;
        }
       
        // 终止条件
     
        // 小问题
        ArrayList<Integer> array = new ArrayList(arr);
        
        array.add(root.val);
        
        // 转化 || 向上一级返回
      getPath(root.left, array, target - root.val);
      getPath(root.right, array, target - root.val);
        }
    }
}

当你root 已经是根节点的时候, 上面标红的两句话都会执行,目标是只执行一次,但是现在问题出现了,

就是因为下面有两个空节点,所有执行两次,所以在二叉树场合的时候,你要注意限制条件, 或者就在root

这一级的时候, 就将程序停止掉

相关文章:

  • 2021-07-02
  • 2022-01-20
  • 2021-11-01
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-06-30
  • 2021-06-24
  • 2021-11-07
  • 2021-06-11
  • 2022-01-29
  • 2021-06-21
相关资源
相似解决方案