码迷,mamicode.com
首页 > 其他好文 > 详细

Same Tree -- leetcode

时间:2015-05-05 19:44:08      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:二叉树   traversal   递归   leetcode   

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.


基本思路:

进行递归操作,判断两个树是否相等。

1. 两树若都为空树,则相等。

2. 两树都不空;根结点的值相等;左子树相等;右子树相等。则该树相等。

在leetcode上实际执行时间为2ms。

/**
 * 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) return true;
        return p && q && 
               p->val == q->val &&
               isSameTree(p->left, q->left) &&
               isSameTree(p->right, q->right);
    }
};


Same Tree -- leetcode

标签:二叉树   traversal   递归   leetcode   

原文地址:http://blog.csdn.net/elton_xiao/article/details/45504417

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!