package tree;
public class SumProperty {
/**
* 查看一颗二叉树的每个节点的值是否都是其左右两个孩子节点值的和
* 当有一个孩子节点为空时,节点值为0
* @param args
*/
public static boolean issumproperty(TreeNode root){
if(root==null||(root.left==null&&root.right==null)){//这个条件不能落下
return true;
}
if(root.value==getvalue(root.left)+getvalue(root.right)){
return issumproperty(root.left)&&issumproperty(root.right);
}
return false;
}
private static int getvalue(TreeNode root) {
if(root==null) return 0;
return root.value;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(10);
root.left = new TreeNode(5);
root.right = new TreeNode(2);
root.left.left = new TreeNode(3);
root.left.right = new TreeNode(5);
root.right.left = new TreeNode(2);
System.out.println(issumproperty(root));
}
}
查看一颗二叉树的每个节点的值是否都是其左右两个孩子节点值的和
最新推荐文章于 2021-04-09 16:04:16 发布