leetcode - 617. 合并二叉树

617. 合并二叉树

class Solution {
    //迭代
    public TreeNode mergeTreesWithStack(TreeNode root1, TreeNode root2) {
        //如果当前root左右子树有一个是空的, 直接把非空的那个返回
        if(root1 == null || root2 == null){
            return root1 == null ? root2 : root1;
        }
        Stack<TreeNode> stack = new Stack<>();
            stack.push(root1);
            stack.push(root2);
            while(!stack.isEmpty()){
                //栈是先进后出的, 后加的2, 所以先出2
                TreeNode cur2 = stack.pop();
                TreeNode cur1 = stack.pop();
                //直接把cur2的值累加到cur1上, 合并当前节点
                cur1.val += cur2.val;
                //假如当前节点左右子树都有才能放到栈里
                if(cur1.left != null && cur2.left != null){
                    stack.push(cur1.left);
                    stack.push(cur2.left);
                }else if(cur1.left == null){ //如果有1为空, 把2非空的那个直接挂到1空的节点上
                    cur1.left = cur2.left;
                }
                if(cur1.right != null && cur2.right != null){
                    stack.push(cur1.right);
                    stack.push(cur2.right);
                }else if(cur1.right == null){
                    cur1.right = cur2.right;
                }
            }
            return root1;
    }

    //递归
    public TreeNode mergeTrees(TreeNode root1, TreeNode root2) {
        //如果1为空, 直接返回直接2非空的那个, 挂到root1上
        if(root1 == null){
            return root2;
        }
        //如果2为空, 直接返回root1, 没节点挂到root1上, 还是原来的节点
        if(root2 == null){
            return root1; 
        }
        //合并当前的头
        root1.val += root2.val;
        //合并左右子树的
        root1.left = mergeTrees(root1.left, root2.left);
        root1.right = mergeTrees(root1.right, root2.right);

        //返回合并的头
        return root1;
    }
}

 

posted on 2022-11-03 13:49  老菜农  阅读(14)  评论(0编辑  收藏  举报

导航