天天看點

資料結構與算法:合并二叉樹

public class MergeTwoTrees {

     static class TreeNode {
        int val = 0;
        TreeNode left = null;
        TreeNode right = null;
     }

    /**
     *
     * @param t1 TreeNode類
     * @param t2 TreeNode類
     * @return TreeNode類
     */
    public TreeNode mergeTrees (TreeNode t1, TreeNode t2) {
        // write code here
        //總體思想(遞歸):以t1為根本,将t2拼接到t1中,具體分一下幾種情況:
        //(1)t1不為空,t2為空
        //(2)t1為空,t2不為空
        //(3)t1與t2都不為空

        if (t1 == null && t2 == null)
            return null;

        //(1)t1不為空,t2為空
        if(t1!=null && t2 == null){
            return t1;
        }
        //(2)t1為空,t2不為空
        if(t1==null && t2!=null){
            return t2;
        }
        //(3)t1與t2都不為空
        if(t1 != null && t2 != null){
            t1.val += t2.val;//合并資料
            t1.left = mergeTrees(t1.left,t2.left);//遞歸左子樹
            t1.right = mergeTrees(t1.right,t2.right);//遞歸右子樹
        }
        return t1;
    }

    public static void main(String[] args) {

    }
}