Header Ad

Leetcode Symmetric Tree problem solution

In this Leetcode Symmetric Tree problem solution we have Given the root of a binary tree, check whether it is a mirror of itself.

Leetcode Symmetric Tree problem solution


Problem solution in Python.

class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        if root is None:
            return True
        stack = [(root, root)]
        
        while stack: 
            node1, node2 = stack.pop()
            if node1 is None and node2 is None:
                pass
            elif node1 is None or node2 is None:
                return False
            elif node1.val != node2.val:
                return False
            else:    
                stack.append((node1.left, node2.right))
                stack.append((node1.right, node2.left))
            
        return True



Problem solution in Java.

class Solution
{
	public boolean isSymmetric(TreeNode root) 
	{
		Queue<TreeNode> q = new LinkedList<>();
		q.add(root);
		q.add(root);

		while(!q.isEmpty()) 
		{
			TreeNode t1 = q.poll();
			TreeNode t2 = q.poll();

			if (t1 == null && t2 == null) 
				continue;
			
			if (t1 == null || t2 == null || t1.val != t2.val)
				return false;
			
			q.add(t1.left);
			q.add(t2.right);
			q.add(t1.right);
			q.add(t2.left);
		}
		return true;
	}
}


Problem solution in C++.

class Solution {
public:

bool sameTree(TreeNode* lr,TreeNode* rr){
    
    if(!lr && !rr)
        return true;
    
    if(!lr || !rr)
        return false;
    
    if(lr->val != rr->val)
        return false;
    
    return sameTree(lr->left,rr->right) && sameTree(lr->right,rr->left);
}

bool isSymmetric(TreeNode* root) {
    if(root == nullptr)
        return true;
    
    return sameTree(root->left,root->right);
}
};


Problem solution in C.

bool dfs(struct TreeNode *root1, struct TreeNode* root2) {
    if(root1 == NULL && root2 == NULL) {
        return true;
    }
    
    if(root1 && root2) {
        if(root1->val == root2->val) {
            return (dfs(root1->left, root2->right) && dfs(root1->right, root2->left));
        }
    }
    
    return false;
}

bool isSymmetric(struct TreeNode* root){
    return dfs(root, root);
}


Post a Comment

0 Comments