11, tree

Subject description:

Two binary inputs A, B, B is judged not substructure A's. (Ps: we agreed empty tree is not a tree any substructure)

Outline of Solution: A, to traverse the tree to the preamble B, if A is B comprises, is not contrary substructure

 public boolean HasSubtree(TreeNode root1,TreeNode root2) {
        if(root1==null || root2==null)
		   return false;
	   StringBuilder sb = new StringBuilder();
	   StringBuilder sb2 = new StringBuilder();
	   String str1 = preOrder(root1,sb);
	   String str2 = preOrder(root2,sb2);
	   if(str1.contains(str2)){
		   return true;
	   }
	 return false;
    }
     public  String  preOrder(TreeNode root,StringBuilder sb){
	   
	   if(root!=null)
		  sb.append(root.val+",");
	   if(root.left!=null){
		   preOrder(root.left,sb);
	   }
	   if(root.right!=null){
		   preOrder(root.right,sb);
	   }
	   return ","+sb.toString();
	   
   }

  Problem-solving ideas II:

/*思路:参考剑指offer
1、首先设置标志位result = false,因为一旦匹配成功result就设为true,
剩下的代码不会执行,如果匹配不成功,默认返回false
2、递归思想,如果根节点相同则递归调用DoesTree1HaveTree2(),
如果根节点不相同,则判断tree1的左子树和tree2是否相同,
再判断右子树和tree2是否相同
3、注意null的条件,HasSubTree中,如果两棵树都不为空才进行判断,
DoesTree1HasTree2中,如果Tree2为空,则说明第二棵树遍历完了,即匹配成功,
tree1为空有两种情况(1)如果tree1为空&&tree2不为空说明不匹配,
(2)如果tree1为空,tree2为空,说明匹配。
 
*/
 
public class Solution {
     public boolean HasSubtree(TreeNode root1,TreeNode root2) {
         boolean result = false ;
             if (root1 != null && root2 != null ){
                 if (root1.val == root2.val){
                     result = DoesTree1HaveTree2(root1,root2);
                 }
                 if (!result){result = HasSubtree(root1.left, root2);}
                 if (!result){result = HasSubtree(root1.right, root2);}
             }
             return result;
     }
     public boolean DoesTree1HaveTree2(TreeNode root1,TreeNode root2){
             if (root1 == null && root2 != null ) return false ;
             if (root2 == null ) return true ;
             if (root1.val != root2.val) return false ;
             return DoesTree1HaveTree2(root1.left, root2.left) && DoesTree1HaveTree2(root1.right, root2.right);
         }
}
 
 
Subject description:
 Operation of a given binary tree, the binary tree is converted into a source image.
 Problem-solving ideas:
 Tree left subtree and right subtree recursively exchange
 
 public void Mirror(TreeNode root) {
        if(root!=null){
            TreeNode temp=null;
            temp=root.left;
            root.left=root.right;
            root.right=temp;
            if(root.left!=null){
                Mirror(root.left);
            }
            if(root.right!=null){
                Mirror(root.right);
            }
            
        }
    }

 

Guess you like

Origin www.cnblogs.com/kobe24vs23/p/11335083.html