根節點到某節點的路徑或者到所有子節點的路徑

肯定前序遍歷

    /**查找根節點到某一節點的路徑*/
    void findPath(TreeNode root, TreeNode target, ArrayList<TreeNode> list){
        if(root == null)
            return;
             // 把當前結點加入到路徑當中來
        list.add(root);
        if(root == target){
            System.out.println("find");
            return;
        }
        if(root.left != null){
            findPath(root.left,target,list);
        }
        if(root.right != null){
            findPath(root.right,target,list);
        }

        //在返回到父節點之前,在路徑上刪除當前節點,這裏非常重要!!!
        list.remove(list.size()-1);
    }

如果求根節點到所有子節點的路徑:
添加

  ArrayList<ArrayList<TreeNode>> ls = new ArrayList<>();

更改結束條件

// 如果爲葉子結點
if(root.left==null && root.right==null){
            ls.add(new ArrayList<>(list));
        }

未測試,思想如上。
參考:https://blog.csdn.net/liuyi1207164339/article/details/50908308
https://www.cnblogs.com/wjf0/p/5873902.html
https://blog.csdn.net/anoobcoder/article/details/79318932 **

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章