LeetCode: 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.

 

使用遍历二叉树的某一种方法(这里使用先序遍历),递归的遍历两棵树,同时比较节点的值,不同则代表两棵树不一样。遍历完毕如果都相同,则两棵树相同。

 

class Solution {
public:
    bool preorder(TreeNode *p, TreeNode *q) {
        if(p == NULL && q == NULL)
        {
            return true;
        }
        else if(p == NULL)
        {
            return false;
        }
        else if(q == NULL)
        {
            return false;
        }
        else if(p->val != q->val)
        {
            return false;
        }
        return (preorder(p->left,q->left) && preorder(p->right,q->right));
    }
    bool isSameTree(TreeNode *p, TreeNode *q) {
        return preorder(p,q);
    }
};

 

你可能感兴趣的:(随记,面试切题)