Wednesday, September 1, 2021

572. Subtree of Another Tree: C# | Define two binary trees are the same | Avoid null pointer exception

 Sept. 1, 2021

C# | Define two binary trees are the same | Avoid null pointer exception

Aug. 31, 2021
Introduction
Design a function to determine if two binary trees are the same, and go through the binary tree using preorder traversal, determine if subRoot TreeNode is the subTree.

FindOne function | isSameTree function | Do not mix two APIs | Avoid null pointer exception to call root.left
It took me less than 15 minutes to make the algorithm pass online judge.

public class Solution {
    public bool IsSubtree(TreeNode root, TreeNode subRoot) {
        
        return FindOne(root, subRoot);
    }
    
    private bool FindOne(TreeNode root, TreeNode subRoot)
    {
          if(root == null || subRoot == null)
                return root == subRoot; 
        
          if(isSameTree(root, subRoot))      
          {
              return true; 
          }
        
          return FindOne(root.left, subRoot) || FindOne(root.right, subRoot);
    }    
    
    public bool isSameTree(TreeNode root, TreeNode subRoot)
    {
        if(root == null || subRoot == null)
        {
            return root == subRoot; 
        }
        
        if(root.val != subRoot.val)
            return false; 
        
        return isSameTree(root.left, subRoot.left) && 
               isSameTree(root.right, subRoot.right);
    }
}

No comments:

Post a Comment