您的位置:首页 > 其它

Data Structure Binary Tree: Check if a given Binary Tree is SumTree

2014-03-29 01:52 330 查看
http://www.geeksforgeeks.org/check-if-a-given-binary-tree-is-sumtree/

#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <stack>
#include <string>
#include <fstream>
using namespace std;

struct node {
int data;
struct node *left, *right;
node() : data(0), left(NULL), right(NULL) { }
node(int d) : data(d), left(NULL), right(NULL) { }
};

bool isleaf(node *root) {
return !root->left && !root->right;
}

bool issumtree(node *root) {
if (!root || isleaf(root)) return true;
int l = 0;
int r = 0;
if (root->left == NULL) l = 0;
else if (isleaf(root->left)) l = root->left->data;
else l = 2 * root->left->data;
if (root->right == NULL) r = 0;
else if (isleaf(root->right)) r = root->right->data;
else r = 2 * root->right->data;
return root->data == l + r && issumtree(root->left) && issumtree(root->right);
}

int main() {
node *root = new node(26);
root->left = new node(10);
root->right = new node(3);
root->left->left = new node(4);
root->left->right = new node(6);
root->right->right = new node(3);
if (issumtree(root)) cout << "yes" << endl;
else cout << "NO" << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐