leetcode-pp / 91alg-5-daily-check

91 天学算法第五期打卡
55 stars 14 forks source link

【Day 14 】2021-09-23 - 100. 相同的树 #29

Open azl397985856 opened 3 years ago

azl397985856 commented 3 years ago

100. 相同的树

入选理由

暂无

题目地址

https://leetcode-cn.com/problems/same-tree/

前置知识

如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。

示例 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

winterdogdog commented 3 years ago
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {boolean}
 */
var isSameTree = function(p, q) {
    if(p === null && q === null) return true;
    if(p === null || q === null) return false;
    if (p.val !== q.val) return false;
    return isSameTree(p.left, q.left) && 
    isSameTree(p.right, q.right)
};
last-Battle commented 3 years ago

思路

关键点

代码

C++ Code:


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if (p == nullptr || q == nullptr) {
            return p == nullptr && q == nullptr;
        }

        if (p->val != q->val) {
            return false;
        }

        return (isSameTree(p->left, q->left) && isSameTree(p->right, q->right));
    }
};

复杂度分析

令 n 为树的节点个数。

xj-yan commented 3 years ago
class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null || q == null) return p == q;
        return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
}

Time Complexity: O(n) Space Complexity: O(h)

BpointA commented 3 years ago

思路

递归。分其中情况讨论,两者均为空,两者只有一个为空,两者均有值但值不同,两者值相同。在值相同时用递归进行下一步判断,到空值出现时停止递归。

Python3代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        if p==None and q==None:
            return True
        elif p==None or q==None:
            return False
        elif p.val!=q.val:
            return False
        else:
            return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)

复杂度

时间复杂度:O(m) ,递归过程遍历节点进行判断,m为两树中节点数较少数的节点数。

空间复杂度:O(m) ,递归过程遍历结点,每次递归空间复杂度为常数

yachtcoder commented 3 years ago

Compare the two nodes (if exists) at the same position from the two trees recursively.

class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        def dfs(n1, n2):
            if not n1 and not n2: return True
            if not n1 or not n2: return False
            if n1.val != n2.val: return False
            return dfs(n1.left, n2.left) and dfs(n1.right, n2.right)
        return dfs(p, q)
leungogogo commented 3 years ago

LC100. Same Tree

Method. Recursion

Main Idea

Code

class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) {
            return true;
        } else if (p == null || q == null || p.val != q.val) {
            return false;
        }
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
}

Complexity Analysis

Time: O(n)

Space: O(h) = O(n)

yanglr commented 3 years ago

思路

可以直接递归来做,也可以用前序遍历 + 中序遍历来做, 同时知道了前序遍历和中序遍历结果, 那么这棵树就是唯一确定的了。

递归

代码

实现语言: C++

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

        return(isSameTree(p->left, q->left) && isSameTree(p->right, q->right)); /* 递归地进行比较  */
    }
};

复杂度分析

前序遍历 + 中序遍历

同时知道了前序遍历和中序遍历结果, 那么这棵树就是唯一确定的了。同理, 如果两棵树的前序遍历完全一样,中序遍历完全一样,那么这棵树就是相同的树。

代码

实现语言: C++

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

        return(preOrder(p) == preOrder(q) && inOrder(p) == inOrder(q));
    }

    string preOrder(TreeNode* root)   /* 根左右 */
    {
        string res;
        if(root == NULL)      // 空节点占位
        {
            res.push_back('#');
            return res;
        }        
        res.push_back(root->val);
        string left = preOrder(root -> left);
        string right = preOrder(root -> right);
        res.insert(res.end(), left.begin(), left.end());
        res.insert(res.end(), right.begin(), right.end());

        return res;
    }

    string inOrder(TreeNode* root)  /* 左根右 */
    {
        string res;
        if(root == NULL)    // 空节点占位
        {
            res.push_back('#');
            return res;
        }
        res = inOrder(root -> left);
        res.push_back(root->val);
        string right = inOrder(root -> right);
        res.insert(res.begin(), right.begin(), right.end());

        return res;
    }    
};

复杂度分析

wangwiitao commented 3 years ago

思路

递归

代码

var isSameTree = function (p, q) {
    if (!p || !q) {
        return !p && !q
    }
    return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
};
HZHENGZHI commented 3 years ago

思路

递归,当p和q都为空时为true,当p或者q其中一个为空时为false,当p.val和q.val不相等时为false 确保p和q的左右子树都为true时,p和q才为相同的两颗树

代码

Java Code:


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
                if(p==null&&q==null)
        {
            return true;
        }
        if(p==null || q==null)
        {
            return false;
        }
        if(p.val!=q.val)
        {
            return false;
        }
        return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
    }
}

复杂度分析

ysy0707 commented 3 years ago

思路:递归

class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
            if(p == null && q == null){
                return true;
            }
            //节点都为空时相同
            else if(p == null || q == null){
                return false;
            }
            //只有一个为空必不相同
            else if(p.val != q.val){
                return false;
            }
            else{
                return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
            }
            //递归,继续判断结点的左右子节点
    }
}

时间复杂度:O(N) 空间复杂度:O(N)

hizhisong commented 3 years ago

DFS

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        bool ans1, ans2;
        if (p == nullptr || q == nullptr) {
            return p == q;
        }

        if (p->val != q->val) {
            return false;
        }

        ans1 = isSameTree(p->left, q->left);
        ans2 = isSameTree(p->right, q->right);

        return ans1 && ans2;
    }
};

有一点tricky

chang-you commented 3 years ago

Thinking

Recursion, postorder.

Java Code

class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) return true;
        if (p == null || q == null) return false;
        if (p.val != q.val) return false;

        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);

    }
}

Complexity

Time = O(n).
Space = O(n).

fzzfgbw commented 3 years ago

思路

递归

代码

func isSameTree(p *TreeNode, q *TreeNode) bool { 
    if p == nil && q==nil{
        return true
    }else if p == nil || q==nil{
        return false
    }else if p.Val !=q.Val{
        return false
    }else{
        return isSameTree(p.Left,q.Left)&&isSameTree(p.Right,q.Right)
    }
}

复杂度分析

zjsuper commented 3 years ago

Idea: recursion

class Solution:
    def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        if p and q:
            return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right) and (p.val == q.val) 
        else:
            return p == q

Time O(N)

Auto-SK commented 3 years ago

思路

深度优先遍历。

代码

class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        if not p and not q:
            return True
        if not p or not q:
            return False
        if p.val != q.val:
            return False
        return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

复杂度

yibenxiao commented 3 years ago

100. 相同的树

思路

遍历整棵树

代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        flag=True
        if p and q:
            if p.val != q.val:
                flag=False
            else:
                return self.isSameTree(q.left,p.left) and self.isSameTree(q.right,p.right)
        if p and not q:
            flag=False
        if not p and q:
            flag=False
        return flag

复杂度

时间复杂度:O(N)

空间复杂度:O(N)

Dana-Dai commented 3 years ago

递归三部曲

class Solution {
public:
    //递归三部曲
    //1.首先要确定递归函数和返回值
    //比较两个树,可直接返回bool
    //2.递归终止条件
    //(1)两个节点都为NULL,返回true
    //(2)一个为空,一个有值,返回false;
    //(3)两个都有值,但不等,返回false;
    //(4)两个都有值,相等,返回true
    //3.确定递归函数
    bool isSameTree(TreeNode* p, TreeNode* q) {
        return compare(p, q);
    }

    bool compare(TreeNode* p, TreeNode* q) {
        if (p == nullptr && q == nullptr) return true;
        else if (p != nullptr && q == nullptr) return false;
        else if (p == nullptr && q != nullptr) return false;
        else if (p->val != q->val) return false;

        return compare(p->left, q->left) && compare(p->right, q->right);
    }
};

迭代(队列)

class Solution {
public:
    //迭代,利用队列
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if (p == nullptr && q == nullptr) return true;
        if (p == nullptr || q == nullptr) return false;
        queue<TreeNode*> que;
        que.push(p);
        que.push(q);
        while (!que.empty()) {
            TreeNode* leftNode = que.front();
            que.pop();
            TreeNode* rightNode = que.front();
            que.pop();
            if (!leftNode && !rightNode) continue;
            if (!leftNode || !rightNode || leftNode->val != rightNode->val) return false;

            que.push(leftNode->left);
            que.push(rightNode->lef);
            que.push(leftNode->right);
            que.push(rightNode->righ);
        }
        return true;
    }
};

时间复杂度为O(n)

MonkofEast commented 3 years ago

100. Same Tree

Click Me

Algo

  1. Judgement must be paried
  2. recur

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        # depth == 1, strick
        if not p and not q: return True
        if not p or not q: return False
        return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

Comp

T: O(N)

S: O(depth)

potatoMa commented 3 years ago

思路


递归DFS

代码


JavaScript Code

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {boolean}
 */
var isSameTree = function(p, q) {
    if (p === null && q === null) return true;
    if (p === null || q === null) return false;
    return p.val === q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
};

复杂度分析


时间复杂度:O(N)

空间复杂度:O(Height)

leo173701 commented 3 years ago

思路: 1)先比较结点p, q 2)再递归比较对应的左右结点

'''python

def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
    if not p or not q:
        return p==q
    else:
        if p.val == q.val:
            return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)

'''

Menglin-l commented 3 years ago

思路:

base case: p和q情况

递归左右子树


代码部分:

class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) return true;
        if ((p == null && q != null) || (p != null && q == null)) return false;
        if (p.val != q.val) return false;

        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
}

复杂度

Time: O(N),N为节点个数

Space: O(height),树的高度

thinkfurther commented 3 years ago

思路

前序遍历以及中序遍历整个tree,如果都相同则两个tree一样

代码

class Solution:
    def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        self.pNodes = []
        self.qNodes = []        
        self.pre_transversal(self.pNodes, p)
        self.pre_transversal(self.qNodes, q)

        if self.pNodes != self.qNodes:
            return False

        self.pNodes = []
        self.qNodes = []
        self.in_transversal(self.pNodes, p)
        self.in_transversal(self.qNodes, q)

        return True if self.pNodes == self.qNodes else False        

    def pre_transversal(self, queue: List, node: Optional[TreeNode]):
        if not node:
            queue.append(None)
            return

        queue.append(node.val)
        self.pre_transversal(queue, node.left)        
        self.pre_transversal(queue, node.right)

    def in_transversal(self, queue: List, node: Optional[TreeNode]):
        if not node:
            queue.append(None)
            return

        self.in_transversal(queue, node.left)
        queue.append(node.val)
        self.in_transversal(queue, node.right)

复杂度

时间复杂度 :O(n)

空间复杂度:O(h)

pophy commented 3 years ago

same tree

思路

Java Code

public boolean isSameTree(TreeNode p, TreeNode q) {
    if (p == null && q == null) {
        return true;
    }
    if (p == null || q == null) {
        return false;
    }
    if (p.val != q.val) {
        return false;
    }
    return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}

时间&空间

zhangzz2015 commented 3 years ago

思路

关键点

代码

C++ Code:

class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {

        if(p==NULL && q==NULL)
            return true; 

        if( (p==NULL&&q) || (p && q==NULL))
            return false;

        if(p->val != q->val)
            return false; 

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

        if(p==NULL && q==NULL)
            return true; 
        if((p==NULL && q) || (p && q==NULL) )
            return false; 

        vector<TreeNode*>  pStack; 
        vector<TreeNode*>  qStack; 
        pStack.push_back(p);
        qStack.push_back(q); 

        while(pStack.size() && qStack.size())
        {
            TreeNode* pTop = pStack.back();
            TreeNode* qTop = qStack.back(); 
            if(pTop->val != qTop->val)
                return false; 
            pStack.pop_back();
            qStack.pop_back(); 
            if( (pTop->left==NULL && qTop->left) || (pTop->left && qTop->left==NULL) )
                return false; 
            else if(pTop->left && qTop->left)
            {
                pStack.push_back(pTop->left); 
                qStack.push_back(qTop->left); 
            }

            if( (pTop->right==NULL && qTop->right) || (pTop->right && qTop->right==NULL) )
                return false; 
            else if(pTop->right && qTop->right)
            {
                pStack.push_back(pTop->right); 
                qStack.push_back(qTop->right); 
            }                        
        }
        return true; 

    }
};
nonevsnull commented 3 years ago

思路

AC

代码

class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        return preorder(p, q);
    }

    public boolean preorder(TreeNode p, TreeNode q) {
        if(p == null && q == null) return true;
        if(p == null || q == null) return false;

        return p.val == q.val && preorder(p.left, q.left) && preorder(p.right, q.right);
    }
}

复杂度

dfs time: 最坏情况,每个node都比较到了,因此O(N) space: 维护递归stack的空间,由递归的层数决定,因此为O(logN);

CoreJa commented 3 years ago

思路

递归求解,同时遍历两个树,判断是否相同

if p.val==q.val:
    return f(p.left,q.left) and f(p.right,q.right)

代码

class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        def traversal(p: TreeNode, q: TreeNode):
            if p is None or q is None:
                if p is None and q is None:
                    return True
                else:
                    return False

            if p.val == q.val:
                return traversal(p.left, q.left) and traversal(p.right, q.right)
            else:
                return False

        return traversal(p, q)
laofuWF commented 3 years ago

💻Code:

# pre-order traversal
# for each node: check if curr node has same value
# recursively check both left and right child
# time: O(N)
# space: O(H)
class Solution:
    def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        if not p and not q:
            return True
        if not p or not q:
            return False

        if p.val != q.val: 
            return False

        leftSame = self.isSameTree(p.left, q.left)
        rightSame = self.isSameTree(p.right, q.right)

        return leftSame and rightSame
erik7777777 commented 3 years ago

code

//use recursion to check every node is exactly the same, pre order traverse, compare the node at the exact same place
public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) return true;
        if (p == null || q == null || p.val != q.val) return false;
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
falconruo commented 3 years ago

思路:

  1. 递归法: 先比较根节点p和q, 如果两个都为空返回true; 如果两个都不为空则分别比较值和左右子树
  2. 迭代法: 用两个辅助队列

复杂度分析:

  1. 时间复杂度: O(min(m,n)), m, n为树的节点数
  2. 空间复杂度:
    • 递归法: O(min(logm, logn)), logm/logn为树的深度, 递归栈的空间
    • 迭代法:O(min(m, n))

代码(C++):

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */

1. 递归法:
class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {

        if (p && q)
            return (p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right));
        else if (!p && !q)
            return true;

        return false;
    }
};
shixinlovey1314 commented 3 years ago

Title:100. Same Tree

Question Reference LeetCode

Solution

Simply do a pre-order traversal, and compare the nodes

Code


class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if (!p && !q)
            return true;

        if ((!p && q) || (p && !q) || (p->val != q->val))
            return false;

        return isSameTree(p->left, q->left) & isSameTree (p->right, q->right);
    }
};

Complexity

Time Complexity and Explaination

O(n): we need to visit each node at least once

Space Complexity and Explaination

O(h): h is the height of the tree. worst case could be O(n)

ZiyangZ commented 3 years ago
//Recursion
class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) return true;
        if (p == null || q == null) return false;
        if (p.val != q.val) return false;
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
}
//Iteration
class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        Queue<TreeNode> queue = new LinkedList<>();
        if (p == null && q == null) return true;
        if (p == null || q == null) return false;
        queue.offer(p);
        queue.offer(q);

        while (!queue.isEmpty()) {
            TreeNode first = queue.poll();
            TreeNode second = queue.poll();
            if (first == null && second == null) continue;
            if (first == null || second == null) return false;
            if (first.val != second.val) return false;
            queue.offer(first.left);
            queue.offer(second.left);
            queue.offer(first.right);
            queue.offer(second.right);
        }
        return true;
    }
}
RocJeMaintiendrai commented 3 years ago

题目

https://leetcode-cn.com/problems/same-tree/

思路

前序, 先对比root节点的值,一样的话对比左右子树

代码

https://leetcode-cn.com/problems/same-tree/

复杂度分析

时间复杂度

O(n)

空间复杂度

O(n)

RocJeMaintiendrai commented 3 years ago

题目

https://leetcode-cn.com/problems/same-tree/

思路

前序, 先对比root节点的值,一样的话对比左右子树

代码

class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p == null && q == null) return true;
        if(p == null || q == null) return false;
        if(p.val != q.val) return false;
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
}

复杂度分析

时间复杂度

O(n)

空间复杂度

O(n)

heyqz commented 3 years ago

code

class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        if not p and not q:
            return True
        elif not p and q:
            return False
        elif not q and p: 
            return False
        return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

complexity

time: O(N) space: O(N)

yingliucreates commented 3 years ago

link:

https://leetcode.com/problems/same-tree/

思路:

recursion

代码 Javascript

function isSameTree(p, q) {
  if (!p && !q) return true;
  if (!p || !q || p.val !== q.val) return false;

  return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}

复杂度分析

空间与时间 O(n)

HackBL commented 3 years ago
st2yang commented 3 years ago

思路

代码

复杂度

florenzliu commented 3 years ago

Explanation

Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

# Approach 1
class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        if not p and not q:
            return True
        if not p or not q:
            return False
        if p.val != q.val:
            return False
        return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

# Approach 2
class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        def isSameNode(a, b):
            if not a and not b:
                return True
            if not a or not b:
                return False
            return a.val == b.val

        queue = [(p,q)]
        while queue:
            p, q = queue.pop(0)
            if not isSameNode(p,q):
                return False
            if p:
                queue.append((p.left, q.left))
                queue.append((p.right, q.right))
        return True          

Complexity

zol013 commented 3 years ago

思路:先check 两棵树的当前节点值是否相等 然后迭代比较两个节点的左节点和右节点值是否相等。

Python 3 code:

class Solution:
    def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        if not p and not q: return True
        if p and not q: return False
        if not p and q: return False

        return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

Time complexity: O(n) Space Complexity: O(logn)

Laurence-try commented 3 years ago

思路

I used BFS yesterday, so, for today, I am using Recursion. While searching the children for a parent of two trees, I directly compared the node value; if they were equal, continue to the farthest leave node, if they were not equal, return False directly.

代码

使用语言:Python3

class Solution:
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        if not q and not p: 
            return True
        if (q and not p) or (not q and p):
            return False
        if q.val != p.val:
            return False
        return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

复杂度分析 时间复杂度:O(n) 空间复杂度:O(n)

ai2095 commented 3 years ago

LC100. Same Tree

https://leetcode.com/problems/same-tree/submissions/

Topics

Similar Questions

Medium

思路

Use both PreOrder and InOrder traversal of the trees.

代码 Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:

        def preOrder(a, b):
            if not a and not b:
                return True

            if (not a and b) or (a and not b) or (a.val != b.val):
                return False

            left = preOrder(a.left, b.left)
            right = preOrder(a.right, b.right)

            return left and right

        def inOrder(a, b):
            if not a and not b:
                return True
            if  (not a and b) or (a and not b):
                return False

            left = inOrder(a.left, b.left)
            if a.val != b.val or not left:
                return False
            right = inOrder(a.left, b.left)
            if not right:
                return False

            return True

        return preOrder(p, q) and inOrder(p, q)

复杂度分析

时间复杂度:O(N)
空间复杂度:O(logN)

Mahalasu commented 3 years ago

思路

递归

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        if not p:
            return not q

        if not q:
            return not p

        if p.val != q.val:
            return False

        return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

T: O(N) S: O(logN)

pan-qin commented 3 years ago

idea: recursion. if p.val==q.val, keep checking their children. Time: O(n) Space: O(h)

class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p==null && q== null)
            return true;
        if(p==null || q==null)
            return false;
        if(p.val != q.val)
            return false;

        return isSameTree(p.left,q.left) && isSameTree(p.right,q.right);
    }
}
a244629128 commented 3 years ago

var isSameTree = function(p, q) {

  if(!p && !q){
       return true;
   }
    if(!p || !q || p.val !== q.val){
        return false;
    }

    return isSameTree(p.left,q.left) && isSameTree(p.right,q.right)
};
// time O(n)
//space O(h)
Maschinist-LZY commented 3 years ago

思路

DFS

代码

C++ Code:


/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
         if (p == q) return true;
        if ((!p || !q) || p->val != q->val) return false;
        return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
    }
};

复杂度分析

tongxw commented 3 years ago

思路

如果根节点都为空,则相同; 如果只有一个根节点为空,则不同; 根节点都不为空的情况,则当节点的值相同,并且左右子树都相同的情况下两树相同,否则不同。

代码

/**
 * @param {TreeNode} p
 * @param {TreeNode} q
 * @return {boolean}
 */
var isSameTree = function(p, q) {
  if (!p && !q) {
    return true;
  } else if (!p || !q) {
    return false;
  } else {
    return p.val === q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
  }
};
kidexp commented 3 years ago

thoughts

标准dfs,就是看当前节点是不是一样,左子树是不是一样,右子树是不是一样

code

class Solution:
    def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        def dfs(root1, root2):
            if not root1 and not root2:
                return True
            if root1 and root2:
                return (
                    root1.val == root2.val
                    and dfs(root1.left, root2.left)
                    and dfs(root1.right, root2.right)
                )
            return False

        return dfs(p, q)

complexity

time complexity O(n)

space complexity O(h) h为 树的高度

akxuan commented 3 years ago

recursion

TC: O(n) n = min(len(p), len(q)) SC: O(h) h = min(h(p), h(q))

class Solution(object):
    def isSameTree(self, p, q):
        """
        :type p: TreeNode
        :type q: TreeNode
        :rtype: bool
        """
         if not q and not p:
            return True 

        if q and p and p.val!=q.val:
            return False

        if (q and not p) or (p and not q) :
            return False 

        return   self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)
qixuan-code commented 3 years ago

LC 100. Same Tree

Ideas DFS 挖个坑,周末学习队列和BFS的解法 comment Runtime: 24 ms, faster than 96.22%

python代码

class Solution:
    def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        if not p and not q:
            return True
        elif not p or not q:
            return False
        elif p.val != q.val:
            return False
        return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)

复杂度分析

chen445 commented 3 years ago

代码

Recursion

class Solution:
    def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        if not p and not q:
            return True
        if not p or not q:
            return False
        if p.val != q.val:
            return False
        return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)

Iteration

class Solution:
    def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        stack=[(p,q)]
        while stack:
            q,p = stack.pop()
            if not q and not p:
                continue
            elif not q or not p or p.val != q.val:
                return False
            stack.extend(([p.left,q.left],[p.right,q.right]))
        return True 

复杂度

Time: O(n)

Space: O(n)