Shirlies
宁静专注认真的程序媛~

题目:

输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)

链接:

http://www.nowcoder.com/practice/6e196c44c7004d15b1610b9afca8bd88?tpId=13&tqId=11170&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

思路:

1、比较父树的某个节点是否与子树的根节点相同,如果相同,转2,否则,继续遍历父树,这是一个递归遍历

2、依次比较父树的左节点和子树的左节点,父树的右节点和子树的右节点,任一次比较不同,则返回false,这也是一个递归遍历

注意:在进行第二步时,如果遍历时子树当前节点为空,而父树当前节点不为空,是返回true,因为父树的节点可以比子树多。

代码:

 1 /*
 2 struct TreeNode {
 3     int val;
 4     struct TreeNode *left;
 5     struct TreeNode *right;
 6     TreeNode(int x) :
 7             val(x), left(NULL), right(NULL) {
 8     }
 9 };*/
10 class Solution {
11 private:
12     bool visitTree(TreeNode *pParentRoot, TreeNode *pSubRoot){
13         if(pParentRoot == NULL && pSubRoot == NULL){
14             return true;
15         }
16         
17         if(pParentRoot == NULL && pSubRoot != NULL){
18             return false;
19         }
20         
21         //注意:如果parentRoot还有值,subRoot为空,是匹配的
22         if(pSubRoot == NULL){
23             return true;
24         }
25         
26         if(pParentRoot->val == pSubRoot->val){
27             bool eq = this->visitTree(pParentRoot->left,pSubRoot->left);
28             if(eq){
29                 return this->visitTree(pParentRoot->right,pSubRoot->right);
30             }
31             
32             return false;
33         }
34         
35         return false;
36     }
37     
38     bool visitParentTree(TreeNode *pParentRoot, TreeNode *pSubRoot){
39         if(pParentRoot == NULL){
40             return false;
41         }
42         
43         bool eq;
44         //如果当前节点相等,则使用visitTree比较以当前节点为根节点的树是否相等
45         if(pParentRoot->val == pSubRoot->val){
46             eq = this->visitTree(pParentRoot,pSubRoot);
47             if(eq){
48                 return true;
49             }
50         }
51         
52         eq = visitParentTree(pParentRoot->left,pSubRoot);
53         if(eq){
54             return true;
55         }
56         
57         return visitParentTree(pParentRoot->right,pSubRoot);
58     }
59 public:
60     bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
61     {
62         if(pRoot1 == NULL || pRoot2 == NULL){
63             return false;
64         }
65         
66         return visitParentTree(pRoot1,pRoot2);
67     }
68     
69 };

 

posted on 2016-09-01 20:15  Shirlies  阅读(275)  评论(0)    收藏  举报