100. Same Tree

来源:互联网 发布:珠三角物流网络 编辑:程序博客网 时间:2024/06/05 04:53

Title

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.

Solutions

  1. 递归
/** * 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) {        /*1. both empty */        if(p==NULL && q == NULL) {            return true;        }        /* 2. both non-empty -> compare them */        if(p!=NULL && q!=NULL){            return ((p->val==q->val) && isSameTree(p->left, q->left) && isSameTree(p->right, q->right));        }        /* 3. one empty, one not -> false */        return false;    }};
/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     struct TreeNode *left; *     struct TreeNode *right; * }; */bool isSameTree(struct TreeNode* p, struct TreeNode* q) {    if (p == NULL && q == NULL) {        return true;    }    if (p == NULL || q == NULL) {        return false;    }    return (p->val == q->val) && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);}

runtime: 4ms

Algorithm

两二叉树,是否结构/元素都相同

isSameTree(TreeNode* p, TreeNode* q):

  1. If both trees are empty then return 1.
  2. Else If both trees are non -empty
    (a) Check data of the root nodes (p->val==q->val)
    (b) Check left subtrees recursively i.e., call isSameTree(p->left, q->left)
    (c) Check right subtrees recursively i.e., call isSameTree(p->right, q->right)
    (d) If a,b and c are true then return 1.
  3. Else return 0 (one is empty and other is not)
0 0
原创粉丝点击