1. 程式人生 > >LeetCode:二叉樹相關應用

LeetCode:二叉樹相關應用

div mage alt sed note col from ret 題目

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

  

LeetCode:二叉樹相關應用