245. Subtree【LintCode java】

來源:互聯網
上載者:User

標籤:探索   int   思路   hat   ||   node   tree   des   tco   

Description

You have two very large binary trees: T1, with millions of nodes, and T2, with hundreds of nodes. Create an algorithm to decide if T2 is a subtree of T1.

A tree T2 is a subtree of T1 if there exists a node n in T1 such that the subtree of n is identical to T2. That is, if you cut off the tree at node n, the two trees would be identical.

Example

T2 is a subtree of T1 in the following case:

       1                3      / \              / T1 = 2   3      T2 =  4        /       4

T2 isn‘t a subtree of T1 in the following case:

       1               3      / \               T1 = 2   3       T2 =    4        /       4
解題:判斷一個二叉樹是不是另一個二叉樹的問題。思路還是很清晰的,但是有些細節還是要注意下的。兩個遞迴,一個用來判斷兩個樹是否完全一樣,這個只要不一樣就返回false。
還有一個遞迴函式是用來返回最終結果的。區別在於,如果第二個函數判斷不等,還有繼續往T2的子樹探索,知道找到一個與T1完全相等的,或者一直到最後也不存在這樣的函數。
比較容易錯的是,在判斷結點值的時候,要先判斷結點是不是null(判空)。
代碼如下:
/** * Definition of TreeNode: * public class TreeNode { *     public int val; *     public TreeNode left, right; *     public TreeNode(int val) { *         this.val = val; *         this.left = this.right = null; *     } * } */public class Solution {    /**     * @param T1: The roots of binary tree T1.     * @param T2: The roots of binary tree T2.     * @return: True if T2 is a subtree of T1, or false.     */    public boolean equal(TreeNode T1, TreeNode T2){        if(T1 == null && T2 == null){            return true;            }else if(T1 == null && T2 != null || T1 != null && T2 == null||T1.val != T2.val){            return false;        }else{            return equal(T1.left, T2.left) && equal(T1.right, T2.right);        }    }    public boolean isSubtree(TreeNode T1, TreeNode T2) {        // write your code here        if(T2 == null)            return true;        if(T1 == null)            return false;        if(equal(T1 , T2))            return true;        else return isSubtree(T1.left, T2)||isSubtree(T1.right, T2);    }}

 

 

245. Subtree【LintCode java】

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.