日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode:二叉树相关应用

發布時間:2023/12/13 编程问答 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LeetCode:二叉树相关应用 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

LeetCode:二叉樹相關應用

基礎知識

617.歸并兩個二叉樹

題目

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樹為基礎展開歸并,首先兩樹都進行先序遍歷,在遍歷的過程中,如果發現一方當前節點不存在,則用另一者的節點橋接過來,如果兩者都存在,則計算其和。

這里有兩個小思考點:

  如果t1節點有,而t2節點沒有,那么無須進行其他操作,并且t1節點的當前子節點都無需遍歷,因為t2全都不存在。同理,t1沒有,t2橋接過來,所有的子節點都無需再遍歷。  

本題主要考察了二叉樹的線性存儲的先序遍歷、遞歸思想。

標準題解

/*** 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;} }

  

?

轉載于:https://www.cnblogs.com/MrSaver/p/8432584.html

總結

以上是生活随笔為你收集整理的LeetCode:二叉树相关应用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。