zoukankan      html  css  js  c++  java
  • 617. 合并二叉树




    方法一:递归。

    class Solution(object):
        # 递归
        def mergeTrees(self, t1, t2):
            """
            :type t1: TreeNode
            :type t2: TreeNode
            :rtype: TreeNode
            """
            if not t1 and not t2:
                return None
            if t1 and not t2:
                return t1
            if not t1 and t2:
                return t2
            t1.val += t2.val
            t1.left = self.mergeTrees(t1.left, t2.left)
            t1.right = self.mergeTrees(t1.right, t2.right)
            return t1
    

    方法二:迭代

    """
    思路:
    	栈中的每个元素都会存放两个根节点,并且栈顶的元素表示当前需要处理的节点。
    	在迭代的每一步中,取出栈顶的元素并把它移出栈,并将它们的值相加。
    	随后分别考虑这两个节点的左孩子和右孩子:
    		如果两个节点都有左孩子,那么就将左孩子入栈;
    		如果只有一个节点有左孩子,那么将其作为第一个节点的左孩子;
    		如果都没有左孩子,那么不用做任何事情。
    		对于右孩子同理。
    	最后返回第一棵树的根节点作为答案。
    """
    class Solution(object):
        def mergeTrees(self, t1, t2):
            """
            :type t1: TreeNode
            :type t2: TreeNode
            :rtype: TreeNode
            """
            # 如果两树有一个为空,则直接返回
            if not (t1 and t2):
                return t1 if not t2 else t2
            # 设栈
            stack = [[t1, t2]]
            while stack:
                node = stack.pop(0)
                if not node[0] or not node[1]:
                    continue
                node[0].val += node[1].val
                # 考虑两树的左孩子
                if not node[0].left:
                    node[0].left = node[1].left
                else:
                    stack.append([node[0].left, node[1].left])
                # 考虑两树的右孩子
                if not node[0].right:
                    node[0].right = node[1].right
                else:
                    stack.append([node[0].right, node[1].right])
            return t1
    
  • 相关阅读:
    Python 中的 __str__ 与 __repr__ 到底有什么差别
    02 LeetCode---链表相加
    01 LeetCode---两数之和
    python 数据结构一 之 线性表
    来自C++的"Const式"傲娇
    string 与 char 字符串区别-1
    超级有爱的并查集入门
    多项式求解
    竞码编程-蓝桥杯模拟赛4-D题
    树的直径-蓝桥杯大臣的旅费
  • 原文地址:https://www.cnblogs.com/panweiwei/p/13661715.html
Copyright © 2011-2022 走看看