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;
}
}
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