劍指Offer的學習筆記(C#篇)-- 樹的子結構

題目描述

輸入兩棵二叉樹A,B,判斷B是否是A的子結構。(ps:咱們約定空樹不是任意一個樹的子結構)

一 . 二叉樹的概念

        樹形結構是一種典型的非線性結構,除了用於表示相鄰關係外,還能夠表示層次關係。每一個結點最多有兩棵子樹。左子樹和右子樹是有順序的,次序不能任意顛倒。即便樹中某結點只有一棵子樹,也要區分它是左子樹仍是右子樹。即爲下圖。。this

C#定義二叉樹:spa

public class BinaryTreeNode
    {
        //節點
        public int Data { get; set; }
        //左子樹
        public BinaryTreeNode leftChild { get; set; }
        //右子樹
        public BinaryTreeNode rightChild { get; set; }
        //數據域
        public BinaryTreeNode(int data)
        {
            this.Data = data;
        }
         //指針域
        public BinaryTreeNode(int data, BinaryTreeNode left, BinaryTreeNode right)
        {
            this.Data = data;
            this.leftChild = left;
            this.rightChild = right;
        }
    }

 

二 . 題目分析

        A-B兩個二叉樹,判斷B是否爲A的子結構。指針

        想法:該題使用遞歸法。步驟爲:在樹A中找到和B的根結點的值同樣的結點;判斷以該節點爲中心的左右子樹是否相同,相同即爲子結構,不一樣繼續遞歸,直到結束。code

三 . 代碼實現:

class Solution
{
    public bool HasSubtree(TreeNode pRoot1, TreeNode pRoot2)
    {
        // write code here
        if(pRoot1 == null || pRoot2 == null)
        {
            return false;
        }
        else
        {
            return Judge(pRoot1,pRoot2);
        }
    }
    public static bool Judge(TreeNode pRoot1, TreeNode pRoot2)
    {
        //解釋說是pRoot2若是所有遍歷完且與pRoot1一一對應,則返回正確
        //若是pRoot2還沒遍歷完,而pRoot1已經遍歷結束,則錯誤。
         if (pRoot2 == null)
         {   
//遞歸成功條件,什麼意思呢,好比B僅有一個節點,且存在和A同樣的節點,那確定是是咯
return true; } if (pRoot1 == null) {
//遞歸失敗條件,若是你一直遞歸下去,A都結束了,還沒找到,那確定不是咯。
return false; } if (pRoot1.val == pRoot2.val) {
//遞歸成功條件2,左右節點都同樣
if (Judge(pRoot1.left,pRoot2.left) && Judge(pRoot1.right,pRoot2.right)) { return true; } } //遞歸 return Judge(pRoot1.left,pRoot2) || Judge(pRoot1.right,pRoot2); } }

PS:該題考點依舊是代碼的魯棒性,因此要格外注意,其實貌似就這麼一處吧if(pRoot1 == null || pRoot2 == null)。。blog

相關文章
相關標籤/搜索