码迷,mamicode.com
首页 > 其他好文 > 详细

树的遍历 | 相同的树

时间:2019-02-14 22:19:34      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:elf   none   ==   stat   str   lse   The   树的遍历   等于   

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

思路1:递归

对于任何两棵相同的树,根节点值相同,且两个左右子树也相同。故我们只需要递归判断p的左子树和q的左子树是否相等,p的右子树和q的右子树是否相等,递归的退出条件为p与q均等于null或其中之一为null

class Solution(object):
    def isSameTree(self, p, q):
        if p is None and q is None:
            return True
        elif p is not None and q is not None:
            return p.val == q.val and self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)
        else:
            return False

思路2: 迭代遍历

对于两棵相同的树,我们在遍历的时候把其当做完全二叉树进行遍历,对于空节点,用#号替代,遍历的结果是相同的。

class Solution(object):
    def isSameTree(self, p, q):
        p = self.pre_trival(p)
        q = self.pre_trival(q)
        return p == q

    def pre_trival(self,p):
        queue = [p]
        result = []
        while len(queue):
            p = queue.pop(0)
            if p:
                result.append(p.val)
                if p.left
                queue.append(p.left)
                queue.append(p.right)
            else:
                result.append("#")
        return result

    def post_trival(self, p):
        if p:
            p.status = 1
        stack = [p]
        result = []
        while len(stack):
                while p:
                    p =p.left
                    if p:
                        p.status = 1
                    stack.append(p)
                p = stack.pop(-1)
                if p and p.status == 1:
                    right = p.right
                    p.status = 0
                    stack.append(p)
                    if right:
                        right.status = 1
                    stack.append(right)
                elif p  is None:
                    result.append("#")
                else:
                    result.append(p.val)
            return result                 

树的遍历 | 相同的树

标签:elf   none   ==   stat   str   lse   The   树的遍历   等于   

原文地址:https://www.cnblogs.com/xmxj0707/p/10380928.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!