【LeetCode大法】Merge Two Binary Trees

来源:互联网 发布:入驻淘宝费用是多少 编辑:程序博客网 时间:2024/05/21 15:44

题意:

Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not.

You need to merge them into a new binary tree. The merge rule is that if two nodes overlap, then sum node values up as the new value of the merged node. Otherwise, the NOT null node will be used as the node of new tree.

原题链接:https://leetcode.com/problems/merge-two-binary-trees/tabs/description

大概的意思就是让你合并两颗树变成一棵树(加起来)。

搞起!搞起!


思路:用递归咯一个一个节点复制过去累加就是了!

简单,完美。


No BB

Show Me Code!

代码:

首先,先定义树出来:

class TreeNode {int val;TreeNode left;TreeNode right;TreeNode(int x) {val = x;}}

然后把树造出来:
/** * 造樹 *  * @param str * @return */public static TreeNode mkTree(String str) {int[] arr = StrToIntArray(str);TreeNode[] nodes = new TreeNode[arr.length + 1];for (int i = 1; i < nodes.length; i++) {if (arr[i - 1] != Integer.MAX_VALUE) {nodes[i] = new TreeNode(arr[i - 1]);} else {nodes[i] = null;}}TreeNode node = null;for (int i = 1; i < nodes.length / 2; i++) {node = nodes[i];if (node == null)continue;node.left = nodes[2 * i];node.right = nodes[2 * i + 1];}return nodes[1];}/** * 裝換 *  * @param str * @return */private static int[] StrToIntArray(String str) {str = str.substring(1, str.length() - 1);String[] strs = str.split(",");int[] arr = new int[strs.length];for (int i = 0; i < arr.length; i++) {if (strs[i].equals("null")) {arr[i] = Integer.MAX_VALUE;} else {arr[i] = Integer.parseInt(strs[i]);}}return arr;}

好了,现在一颗树就在我们面前了,开始解决问题:合并!

public static TreeNode solution(TreeNode t1, TreeNode t2) {if (t1 == null || t2 == null) {return null;}//在当前树节点上把源两颗树的该位置节点拿下来合并再赋给新树的该节点TreeNode t = new TreeNode((t1 == null ? 0 : t1.val) + (t2 == null ? 0 : t2.val));t.left = solution(t1.left, t2.left);//递归搞起t.right = solution(t1.right, t2.right);//递归搞起return t;}

这个,一颗新的树就出现了!

完美