1. 程式人生 > 其它 >【資料結構】二叉樹中的列表 Linked List in Binary Tree

【資料結構】二叉樹中的列表 Linked List in Binary Tree

目錄

二叉樹中的列表 Linked List in Binary Tree7

一顆以root為根的二叉樹,和一個head 為首節點的連結串列。如果在二叉樹中存在一個一直向下的路徑,並且每一個節點的值都對應head為首節點的連結串列的值,那麼就返回true,否則返回 false

head =  [4,2,8]
root =[1,4,4,null,2,2,null,1,null,6,8,null,null,null,null,1,3]
true

思路

首先思考的是通過遞迴來解決,設計一個遞迴方法來處理。

方法主要用來判斷樹的節點

tnode連結串列的節點lnode向下尋找是否存在一條path可以與lnode節點開始的連結串列匹配。如果匹配就返回true,否則false。

接著就是遞迴的結束條件:

1 如果list已經匹配完了,那麼就是存在的,true

2 如果tree都訪問到null空節點,那麼就不存在,false

3 如果節點對應的值不相等,false

4 如果不是上面的3種情況,說明目前來說匹配成功,那就繼續遞迴。從tnode的左右子樹,開始與lnode.next來匹配。

  public boolean isSubPath(ListNode head, TreeNode root) {
        if (head==null){
            return true;
        }
        if (root == null){
            return false;
        }
        if (head.val==root.val&&judge(root,head)){
            return true;
        }
        return isSubPath(head,root.left)||isSubPath(head,root.right);
    }

    public boolean judge(TreeNode root,ListNode head){
        if (head == null){
            return true;
        }
        if (root == null){
            return false;
        }
        if (head.val!=root.val){
            return false;
        }
        return judge(root.left,head.next)||judge(root.right,head.next);
    }

Tag

binary search