leetcode 965. 单值二叉树 c++

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/glw0223/article/details/88735765

965. 单值二叉树

分析

  • 递归方式的退出条件,可能有多个
  • 可能需要两个函数才能完成递归
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isUnivalTree(TreeNode* root) {
        if(root==nullptr){
            return true;
        }
        return _isUnivalTree(root,root->val);
    }
private:
    bool _isUnivalTree(TreeNode* root, int value){
        if(root==nullptr){
            return true;
        }else if (root->val == value){
            return _isUnivalTree(root->left,value) && _isUnivalTree(root->right,value);
        }else{
            return false;
        }
    }
};

猜你喜欢

转载自blog.csdn.net/glw0223/article/details/88735765