第六周Same Tree

来源:互联网 发布:mac投影仪只显示桌面 编辑:程序博客网 时间:2024/06/14 17:00

Same Tree

Leetcode algorithms problem 100:Same Tree

  • 问题描述

    Given two binary trees, write a function to check if they are equal or not.
    Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

  • 问题提示

  • 思路

    使用递归,首先返回节点为NULL时的相等情况;两个节点都是有效指针时,如果根值不一样,返回false,一样则进入递归:根的左侧树是相同的(递归)&&根的右侧树是相同的(递归),否则返回false

代码

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

时间复杂度: O(n)
空间复杂度: O(2^n)


原创粉丝点击