General Template for Tree Problems using the beauty of DFS
2270

Well many of us know binary tree and its importance but many begineers struggle to solve even easy Binary tree programs , if your one among them ? Then this guide is for you my friend .

Requirements to understand  :
	1. Recursion
	2. Backtracking.
	3. dfs 

Well binary trees are non-linear and recursive Data-Structure which makes them little hard

Points to remember :
1 . Subtree are also trees
2 . Considering the above point just calling the method over the left subtree and right subtree recursively will solve almost any problem

For instance below is the implementation in JAVA for - https://leetcode.com/problems/maximum-depth-of-binary-tree/

public int maxDepth(TreeNode root){
        if(root == null){
            return 0;
        }
        int left = maxDepth(root.left);
        int right = maxDepth(root.right);

        return Math.max(left,right)+1;
    }

As you guys could see we are calling the same method recursively again over the left subtree and right subtree
in the lines

" int left = maxDepth(root.left) " and " int right = maxDepth(root.right) "
and calculatiing the depth for this program.

This above template can be used for many problems like invert binary tree , diameter of a tree ... with some little addition of code like swapping the left and right subtree for the invert binary tree program

The template can be little modified to solve some more binary tree programs

For instance the program Same tree : https://leetcode.com/problems/same-tree/

public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p == null && q == null)
            return true;
        if( p == null || q == null )
            return false;
        
        return p.val == q.val && isSameTree(p.left,q.left) &&
            isSameTree(p.right,q.right);
    }

All we did is added another base case and made both base cases to support another treeNode
and the others remain the same i.e calling the method again for the left and right Subtree recursively and compare the values for this specific program

So guys i believe you got an idea on how to approach binary tree programs and if you ever feel lost in your way then discuss section in leetcode is your greatest friend and this is one of the feature which i love the most in leetcode Making it stand out from other online judging websites

If you found this useful do upvote !
Happy coding :)

Comments (1)