Skip to content

100. 相同的树 #21

Closed
Closed
@sailei1

Description

@sailei1

示例 1:

输入:

        1         1
       / \       / \
      2   3     2   3

     [1,2,3],   [1,2,3]

输出: true
示例 2:

输入:

           1        1
          /           \
         2             2

        [1,2],     [1,null,2]

输出: false
示例 3:

输入:

          1         1
         / \       / \
        2   1     1   2

       [1,2,1],   [1,1,2]

输出: false

解法:
1 先对比 当前值 相同 再对比左右
2 有一个存在 的情况 返回false
3 递归

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {boolean}
 */
var isSameTree = function(p, q) {
    // console.log(p);
    // console.log(q);
       
      if(p&&q && p.val == q.val){   
          return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);
      }else{
          if(p||q){
            return false;
          }else{
              return true;
         }
       }
   //  解法2
    //  return JSON.stringify(p) === JSON.stringify(q)    树 本身就是object 直接转 json  对比 最快

    
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions