2017-10-01 27 views
0

给定两个二叉树t1和t2,确定第二棵树是否是第一棵树的子树。二叉树t中顶点v的子树是一棵由v及其所有后代t组成的树。确定树t1中是否存在顶点v(可能是无),使得t1中顶点v(可能为空)的子树等于t2。codefights isSubTress只有一个隐藏测试用例不能通过

// 
    // Definition for binary tree: 
    // function Tree(x) { 
    // this.value = x; 
    // this.left = null; 
    // this.right = null; 
    // } 
    function isSubtree(t1, t2) { 

     function findroot(t1,t2){ 
     if(t2==null){ 
      return true; 
     }else if(t1==null){ 
      if(t2==null){ 
      return true; 
      }else{ 
      return false; 
      } 
     }else if((
      t1.value == t2.value && machedTree(t1,t2)) || findroot(t1.left,t2) || findroot(t1.right,t2)){ 
      return true; 
     }else{ 
      return false 
     } 
     } 
     function machedTree(t1,t2){ 
     if((t1 == null && t2 == null) 
      &&(t1 == null && t2==null)){ 
      return true; 
     }else if(t2 == null || 
      ((t1 != null && t2!=null) 
      && machedTree(t1.left,t2.left) 
      &&t1.value == t2.value 
      &&machedTree(t1.right,t2.right))){ 
      return true; 
     }else{ 
      return false; 
     } 

     } 
     return findroot(t1,t2) 
    } 

只有一个隐藏测试用例无法通过。你有任何想法,是错误的代码

回答

0

功能isSubtree(T1,T2){

 function findroot(t1,t2){ 
     if(t2==null){ 
      return true; 
     }else if(t1==null){ 
      return false; 
     }else if((
      t1.value == t2.value && machedTree(t1,t2)) || findroot(t1.left,t2) || findroot(t1.right,t2)){ 
      return true; 
     }else{ 
      return false 
     } 
     } 
     function machedTree(t1,t2){ 
     if(t1==null && t2 == null){ 
      return true; 
     } 
     else if((t2 != null && t1 != null) 
      && machedTree(t1.left,t2.left) 
      && (t1.value === t2.value) 
      &&machedTree(t1.right,t2.right)){ 
      return true; 
     }else{ 
      return false; 
     } 

     } 
     return findroot(t1,t2) 
    } 
相关问题