zoukankan      html  css  js  c++  java
  • 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
    时间才能证明一切,选好了就尽力去做吧!
  • 相关阅读:
    SharePoint Forums使用
    使用JS隐藏MOSS菜单
    缓存
    异步委托
    一个层动态放大的例子的一些知识点
    petshop之购物车再思考
    设置防止攻击session(疑惑)
    petshop异步和多线程
    Profile在petshop
    一个简单的显示隐藏知识点
  • 原文地址:https://www.cnblogs.com/tingxilin/p/10739506.html
Copyright © 2011-2022 走看看