Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

617. 合并二叉树 #70

Open
yankewei opened this issue Nov 4, 2020 · 1 comment
Open

617. 合并二叉树 #70

yankewei opened this issue Nov 4, 2020 · 1 comment
Labels
题目类型为树结构 深度优先搜索 题目包含深度优先搜索解法 简单 题目难度为简单

Comments

@yankewei
Copy link
Owner

yankewei commented Nov 4, 2020

给定两个二叉树,想象当你将它们中的一个覆盖到另一个上时,两个二叉树的一些节点便会重叠。

你需要将他们合并为一个新的二叉树。合并的规则是如果两个节点重叠,那么将他们的值相加作为节点合并后的新值,否则不为 NULL 的节点将直接作为新二叉树的节点。

示例 1:

输入:

	Tree 1                     Tree 2                  
          1                         2                             
         / \                       / \                            
        3   2                     1   3                        
       /                           \   \                      
      5                             4   7                  

输出:
合并后的树:

	     3
	    / \
	   4   5
	  / \   \ 
	 5   4   7

注意: 合并必须从两个树的根节点开始。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/merge-two-binary-trees
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

@yankewei yankewei added 题目类型为树结构 简单 题目难度为简单 深度优先搜索 题目包含深度优先搜索解法 labels Nov 4, 2020
@yankewei
Copy link
Owner Author

yankewei commented Nov 4, 2020

深度优先搜索

很简单的一个深度优先搜索的题目

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func mergeTrees(t1 *TreeNode, t2 *TreeNode) *TreeNode {
    if t1 == nil {
        return t2
    }
    if t2 == nil {
        return t1
    }

    t1.Val += t2.Val
    t1.Left = mergeTrees(t1.Left, t2.Left)
    t1.Right = mergeTrees(t1.Right, t2.Right)
    return t1
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
题目类型为树结构 深度优先搜索 题目包含深度优先搜索解法 简单 题目难度为简单
Projects
None yet
Development

No branches or pull requests

1 participant