编程题-树的子结构

编程题-树的子结构

  • 题目
  • c#代码

题目

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

示例1
输入
{8,8,#,9,#,2,#,5},{8,9,#,2}
返回值
true

c#代码


public class TreeNode
{public int val;public TreeNode left;public TreeNode right;public TreeNode (int x){val = x;}
}class Solution
{public bool HasSubtree(TreeNode pRoot1, TreeNode pRoot2){if(pRoot1==null || pRoot2==null)return false;bool result=false;if(pRoot1.val==pRoot2.val)result=T1HaveT2(pRoot1,pRoot2);if(!result)result =HasSubtree(pRoot1.left,pRoot2);if(!result)result =HasSubtree(pRoot1.right,pRoot2);return result;}public bool T1HaveT2(TreeNode pRoot1, TreeNode pRoot2){bool result=true;if(pRoot1.val!=pRoot2.val)return false;if(pRoot2.left!=null){if(pRoot1.left==null)return false;result=T1HaveT2(pRoot1.left,pRoot2.left);}if(result==false)return result;if(pRoot2.right!=null){if(pRoot1.right==null)return false;result=T1HaveT2(pRoot1.right,pRoot2.right);}return result;}}

编程题-树的子结构

编程题-树的子结构

  • 题目
  • c#代码

题目

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

示例1
输入
{8,8,#,9,#,2,#,5},{8,9,#,2}
返回值
true

c#代码


public class TreeNode
{public int val;public TreeNode left;public TreeNode right;public TreeNode (int x){val = x;}
}class Solution
{public bool HasSubtree(TreeNode pRoot1, TreeNode pRoot2){if(pRoot1==null || pRoot2==null)return false;bool result=false;if(pRoot1.val==pRoot2.val)result=T1HaveT2(pRoot1,pRoot2);if(!result)result =HasSubtree(pRoot1.left,pRoot2);if(!result)result =HasSubtree(pRoot1.right,pRoot2);return result;}public bool T1HaveT2(TreeNode pRoot1, TreeNode pRoot2){bool result=true;if(pRoot1.val!=pRoot2.val)return false;if(pRoot2.left!=null){if(pRoot1.left==null)return false;result=T1HaveT2(pRoot1.left,pRoot2.left);}if(result==false)return result;if(pRoot2.right!=null){if(pRoot1.right==null)return false;result=T1HaveT2(pRoot1.right,pRoot2.right);}return result;}}