Find the slope of a binary tree

describe

Find the inclination of a binary tree, where the inclination of a node is defined as the absolute value of the difference between the "sum of left subtree elements" and "the sum of right subtree elements" (the element value of an empty node is 0), the inclination of a binary tree Degree is defined as the sum of the inclinations of all nodes.

A binary tree node is defined as follows:

struct TreeNode {

    int val;

    struct TreeNode *left;

    struct TreeNode *right;

};

The code of the title part has been completed, you only need to add and submit the following functions:

int findTilt(struct TreeNode* root);

enter

The input is a number of integers (not more than 512) representing the node element value of a binary tree in sequential representation, where 0 indicates that the corresponding node of the binary tree is empty. Input ends with -1. 

output

Output the slope of the binary tree.

sample input

1 2 3 -1

Sample output

 1

 

#include<bits/stdc++.h>
using namespace std;
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
};

int s;
int dfs(struct TreeNode* t)
{
    if(t==NULL)
        return 0;
    int l=dfs(t->left);
    int r=dfs(t->right);
    s=s+abs(l-r);
    return l+r+t->val;
}
int findTilt(struct TreeNode* root)
{
    dfs(root);
    return abs(s);
}

TreeNode*creat()
{
    int front=1,rear=0,x;
    TreeNode*qu[1005],*t,*root=NULL;
    while(scanf("%d",&x)!=EOF,x!=-1)
    {
        if(x==0)
            t=NULL;
        else
        {
            t=new TreeNode;
            t->val=x;
              t->left=NULL;
            t->right=NULL;
        }
        qu[++rear]=t;
        if(rear==1)
            root=t;
        else
        {
            if(t&&qu[front])
            {
                if(rear%2==0)
                    qu[front]->left=t;
                else 
                    qu[front]->right=t;
            }
            if(rear%2==1)
                front++;
        }
    }
    return root;
}
intmain ()
{
    TreeNode*x=creat();
    printf("%d\n",findTilt(x));
    return 0;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325361918&siteId=291194637