469 Same Tree

原题网址:https://www.lintcode.com/problem/same-tree/description

描述

检查两棵二叉树是否等价。等价的意思是说,首先两棵二叉树必须拥有相同的结构,并且每个对应位置上的节点上的数都相等。

您在真实的面试中是否遇到过这个题?  

样例

    1             1
   /            / 
  2   2   and   2   2
 /             /
4             4

就是两棵等价的二叉树。

    1             1
   /            / 
  2   3   and   2   3
 /               
4                 4

就不是等价的。

 

思路:采用前序遍历判断。

a和b都为NULL,return true;

a和b只有其中一个为NULL,return false;

如果节点值不相等,return false;

递归判断左右子树,如果左右子树都相等,返回true;否则,返回false;

 

AC代码:

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */

class Solution {
public:
    /**
     * @param a: the root of binary tree a.
     * @param b: the root of binary tree b.
     * @return: true if they are identical, or false.
     */
    bool isIdentical(TreeNode * a, TreeNode * b) {
        // write your code here
    if (a==NULL&&b==NULL)
    {
        return true;
    }
    if (a==NULL||b==NULL)
    {
        return false;
    }
    if (a->val!=b->val)
    {
        return false;
    }
    bool x=isIdentical(a->left,b->left);
    bool y=isIdentical(a->right,b->right);
    return x&&y;
    
    }
};

 

PS:

初始代码直接递归左右子树,然后返回true,如下:

isIdentical(a->left,b->left);
isIdentical(a->right,b->right);
return true;

这种代码没有层层返回结果,判断左右子树是否都相同(即函数返回值是否都为true),所以导致只要根节点值相同就返回true,结果错误。

【若在某个非根节点a和b值不相同, 该层函数结果是false,但是没有反馈出去。】

其他参考:

https://www.cnblogs.com/grandyang/p/4053384.html

 

原文地址:https://www.cnblogs.com/Tang-tangt/p/9254151.html