LeetCode:二叉树相关应用
LeetCode:二叉樹相關(guān)應(yīng)用
基礎(chǔ)知識(shí)
617.歸并兩個(gè)二叉樹
題目
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.
Example 1:
Input: Tree 1 Tree 2 1 2 / \ / \ 3 2 1 3 / \ \ 5 4 7 Output: Merged tree:3/ \4 5/ \ \ 5 4 7?
Note:?The merging process must start from the root nodes of both trees.
分析
以t1樹為基礎(chǔ)展開歸并,首先兩樹都進(jìn)行先序遍歷,在遍歷的過(guò)程中,如果發(fā)現(xiàn)一方當(dāng)前節(jié)點(diǎn)不存在,則用另一者的節(jié)點(diǎn)橋接過(guò)來(lái),如果兩者都存在,則計(jì)算其和。
這里有兩個(gè)小思考點(diǎn):
如果t1節(jié)點(diǎn)有,而t2節(jié)點(diǎn)沒有,那么無(wú)須進(jìn)行其他操作,并且t1節(jié)點(diǎn)的當(dāng)前子節(jié)點(diǎn)都無(wú)需遍歷,因?yàn)閠2全都不存在。同理,t1沒有,t2橋接過(guò)來(lái),所有的子節(jié)點(diǎn)都無(wú)需再遍歷。
本題主要考察了二叉樹的線性存儲(chǔ)的先序遍歷、遞歸思想。
標(biāo)準(zhǔn)題解
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/ class Solution {public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {if(t1==null)return t2;if(t2==null)return t1;t1.val +=t2.val;t1.left = mergeTrees(t1.left,t2.left);t1.right = mergeTrees(t1.right,t2.right);return t1;} }
?
轉(zhuǎn)載于:https://www.cnblogs.com/MrSaver/p/8432584.html
總結(jié)
以上是生活随笔為你收集整理的LeetCode:二叉树相关应用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: UML类图关系(泛化 、继承、实现、依赖
- 下一篇: flask-session总结