965. 单值二叉树(深搜/广搜)

 

 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 }

猜你喜欢

转载自www.cnblogs.com/NiBosS/p/12032204.html