Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Thursday, August 17, 2017

Evaluate Expression Tree


Explanation:

Go to leaf nodes get their values and then check for expression (*/-+) evaluate and then return it.

Code:
class GfG{
      public int evalTree(Node root)
      {
          if(root==null)
          return 0;
          if(root.left==null && root.right==null)
          {
              return Integer.parseInt(root.data);
          }
          int left=evalTree(root.left);
          int right=evalTree(root.right);
          if(root.data.equals("+"))
         {
            // System.out.println(left+right);
             return left+right;
         }
          if(root.data.equals("-"))
          {
             
            // System.out.println(left-right);
              return left-right;}
          if(root.data.equals("*"))
          {
             
            // System.out.println(left*right);
              return left*right;}
          return left/right;
      }
}

0 Comments:

Post a Comment

Stats