LeetCode--Same Tree

来源:互联网 发布:淘宝能卖二手货吗 编辑:程序博客网 时间:2024/06/15 11:19

Given two binary trees, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

Example 1:

Input:     1         1          / \       / \         2   3     2   3        [1,2,3],   [1,2,3]Output: true

Example 2:

Input:     1         1          /           \         2             2        [1,2],     [1,null,2]Output: false

Example 3:

Input:     1         1          / \       / \         2   1     1   2        [1,2,1],   [1,1,2]Output: 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&&q)||(!q&&p)) return false;        if(!p&&!q) return true;        return (p->val==q->val&&isSameTree(p->left,q->left)&&isSameTree(p->right,q->right));    }};
原创粉丝点击