二叉树递归(DFS)

    1. /**
    2. * Definition for a binary tree node.
    3. * struct TreeNode {
    4. * int val;
    5. * TreeNode *left;
    6. * TreeNode *right;
    7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
    8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
    10. * };
    11. */
    12. class Solution {
    13. public:
    14. bool isUnivalTree(TreeNode* root) {
    15. int co_val=root->val;
    16. bool result=dfs(root,co_val);
    17. return result;
    18. }
    19. bool dfs(TreeNode* root,int co_val){
    20. if(root==NULL){
    21. return true;
    22. }
    23. if(root->val!=co_val){
    24. return false;
    25. }
    26. bool a1=dfs(root->left,co_val);
    27. bool a2=dfs(root->right,co_val);
    28. return a1&&a2;
    29. }
    30. };