1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 private int val; 12 private boolean flag=true; 13 public boolean isUnivalTree(TreeNode root) { 14 if(root==null) return true; 15 val=root.val; 16 dfs(root); 17 return flag; 18 } 19 void dfs(TreeNode root){ 20 if(!flag||root==null) return; //剪枝 21 if(root.val!=val){ 22 flag=false; 23 return; 24 } 25 dfs(root.left); 26 dfs(root.right); 27 } 28 }