100. Same Tree

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

思路

直接递归进行比较,DFS算法。

  • 如果都为NULL,返回true
  • 如果都不为NULL,当val相同时,递归比较左右子节点
  • 以上都不返回true,则为false

判断x为0或NULL,可以使用 if( x == NULL或0),也可以采用 if( !x ) 这种简洁的书写方式

c++11

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

results matching ""

    No results matching ""