Inverting Binary Tree #LeetCode_June _2020 Challenge Day 1


For Quoestion click Here

First we traverse the tree Using Postorder traversal, we swap left child and right child of each node and return to root this processcan be done using recursion.We define swap function that first processes left subtree and then right sub tree

Python Code:

Method1:
class TreeNode:

    def __init__(self, val=0, left=None, right=None):
       self.val = val
          self.left = left
         self.right = right

class Solution:
    
    def invertTree(self, root: TreeNode) -> TreeNode:
        if root:
            root.left,root.right = root.right,root.left
            self.invertTree(root.left)
            self.invertTree(root.right)

        return root 
Method2:
# Definition for a binary tree node.

class TreeNode:

    def __init__(self, val=0, left=None, right=None):

        self.val = val
        self.left = left
        self.right = right
class Solution:
    def swap(self,root):
        if not root:
            return
        #swap child pointers
        self.swap(root.left)
        self.swap(root.right)
        root.left,root.right = root.right,root.left 
    def invertTree(self, root: TreeNode) -> TreeNode:
        self.swap(root)
        return root
    #Hidden Driver Code

CONCLUSION:
This Algorithms Takes Big O(n) Time Complexity
Leave a Comment Below If You Have Better Solution

Post a Comment

0 Comments