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; }
相关文章推荐
- Check if a given Binary Tree is SumTree
- Check if the given binary tree is BST or not.
- Data Structure Binary Tree: How to determine if a binary tree is height-balanced?
- Data Structure Binary Tree: Convert a given tree to its Sum Tree
- Data Structure Binary Tree: Check for Children Sum Property in a Binary Tree
- Given a binary tree, determine if it is height-balanced. For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never diffe
- Data Structure Binary Tree: Convert an arbitrary Binary Tree to a tree that holds Children Sum Property
- 是否是二叉搜索树 check if it is binary search tree
- ch4.7: given 2 huge Binary tree t1, t2(>1millon nodes), decide if one tree is subtree of another one
- LeetCode题目笔记(四) -- Check if a binary tree is balanced
- A program to check if a binary tree is BST or not
- Data Structure Binary Tree: Convert a given Binary Tree to Doubly Linked List
- Data Structure Binary Tree: Print ancestors of a given binary tree node without recursion
- [面试题]Amazon: Given two binary trees,if the first tree is subtree of the second one
- Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum. For example: Given the below binary tree andsum =
- Data Structure Array: Find if there is a subarray with 0 sum
- Data Structure Binary Tree: Construct Tree from given Inorder and Preorder traversals
- Data Structure Binary Tree: Construct Full Binary Tree from given preorder and postorder traversals
- 【Leetcode】Given a binary tree, check whether it is a mirror of itself
- Data Structure Linked List: Function to check if a singly linked list is palindrome