• leetcode每日刷题计划-简单篇day10


    跳题,不熟悉的留到周末再做。

    保持冷静,不信画饼。

    num 100 相同的树 Same Tree

    做法可能不是特别简洁,注意一下。最后判断完子树以后,要确定根的数值是一样的

    然后在isleaf的判定先要确定NULL

    /**
     * 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 isleaf(TreeNode*p)
        {
            if (p==NULL) return false;
            if(p->left==NULL && p->right==NULL)
                return true;
            else 
                return false;
        }
        bool isSameTree(TreeNode* p, TreeNode* q) {
            if(isleaf(p) && isleaf(q)) 
            {
                if(p->val==q->val)
                    return true;
                else 
                    return false;
            }
            else
            {
                if(isleaf(p) && !isleaf(q))
                    return false;
                if(!isleaf(p) && isleaf(q))
                    return false;
                if(p==NULL && q!=NULL)
                    return false;
                if(p!=NULL && q==NULL)
                    return false;
                if(p==NULL && q==NULL)
                    return true;
                if((p->val==q->val) && isSameTree(p->left,q->left) && isSameTree(p->right,q->right))
                    return true;
                else return false;
            }
            return false;
        }
    };
    View Code

     num 104 二叉树的最大深度 Maximum Depth of Binary Tree

    注意判断root==NULL

    /**
     * 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:
        int maxDepth(TreeNode* root) {
            if(root==NULL)
                return 0;
            if(root->left==NULL && root->right==NULL)
                return 1;
            if(root->left==NULL)
                return(maxDepth(root->right)+1);
            if(root->right==NULL)
                return (maxDepth(root->left)+1);
            else
                return (max(maxDepth(root->left),maxDepth(root->right))+1);
        }
    };
    View Code
    时间才能证明一切,选好了就尽力去做吧!
  • 相关阅读:
    用R语言实现对不平衡数据的四种处理方法
    用R语言实现对不平衡数据的四种处理方法
    Java学习——Applet画8个同心圆
    Java学习——Applet画8个同心圆
    Java学习——Applet写字符串(调字体)
    Java学习——Applet写字符串(调字体)
    ZOJ 2913 Bus Pass (近期的最远BFS HDU2377)
    机房结账功能分析
    数据结构记录--排序
    C#创建PDF文档
  • 原文地址:https://www.cnblogs.com/tingxilin/p/10739506.html
Copyright © 2020-2023  润新知