Skip to content

Instantly share code, notes, and snippets.

@cc2011
Created August 22, 2017 07:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cc2011/a0c7fd9b4e488116c11510b4f94242f8 to your computer and use it in GitHub Desktop.
Save cc2011/a0c7fd9b4e488116c11510b4f94242f8 to your computer and use it in GitHub Desktop.
equal-tree-partition
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean checkEqualTree(TreeNode root) {
return checkValid(getSum(root), root, root);
}
public int getSum(TreeNode node) {
if(node == null)
return 0;
int sum = node.val + getSum(node.left) + getSum(node.right);
return sum;
}
public boolean checkValid(int sum, TreeNode root, TreeNode curr) {
if(curr == null)
return false;
return checkValid(sum, root, curr.left) || checkValid(sum, root, curr.right) || (root != curr && sum == 2*getSum(curr));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment