Merge Two Binary Trees

https://leetcode.com/problems/merge-two-binary-trees/description/

Merge Two Binary Trees_第1张图片

二叉树

二叉树的遍历方式:

  • 前序遍历(NLR)
  • 中序遍历(LNR)
  • 后序遍历(LRN)
首先定义一个二叉树类,左节点和右节点
public class TreeNode {

    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}

求解

 //就是一个递归调用的过程
 public TreeNode mergeTrees(TreeNode t1, TreeNode t2) {
        if (t1 == null){
            return t2;
        }
        if (t2 == null){
            return  t1;
        }
        t1.val = t1.val + t2.val;
        t1.left = mergeTrees(t1.left,t2.left);
        t1.right = mergeTrees(t1.right,t2.right);
        return t1;
    }

构建二叉树

    /**
     * 根据NLF构造二叉树
     * 构建二叉树
     */
    public TreeNode buildTree(int[] vals){
        TreeNode treeNode = null;

        return treeNode;
    }

你可能感兴趣的:(Merge Two Binary Trees)