leetcode算法题-剑指Offer篇(8)

1、合并两个排序的链表

1.1 题目描述:

输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。

1.2 题解
1.2.1新建链表,引入伪头结点
     public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode result = new ListNode(0), cur = result;
        while(l1 != null && l2 != null) {
            if(l1.val < l2.val) {
                cur.next = l1;
                l1 = l1.next;
            }
            else {
                cur.next = l2;
                l2 = l2.next;
            }
            cur = cur.next;
        }
        cur.next = l1 != null ? l1 : l2;//将剩下的链表整条插入新链表的后端
        return result.next;
    }
    }

2、树的子结构

2.1 题目描述:

输入两棵二叉树A和B,判断B是不是A的子结构。(约定空树不是任意一个树的子结构)

2.2 题解
2.2.1递归
    public boolean isSubStructure(TreeNode A, TreeNode B) {
        if (A == null || B == null)
            return false;
        return help(A, B) || isSubStructure(A.left, B) || isSubStructure(A.right, B);
    }
 /**
     * 当节点 B 为空:说明树 B已匹配完成(越过叶子节点),因此返回 true ;
     * 当节点 A 为空:说明已经越过树 A 叶子节点,即匹配失败,返回 false ;
     * 当节点 A 和 B 的值不同:说明匹配失败,返回 false ;
     *
     * @param A
     * @param B
     * @return
     */
   public boolean help(TreeNode A, TreeNode B) {
        if (B == null)
            return true;
        if(A==null||A.val != B.val)
            return false;
        return (help(A.left, B.left) && help(A.right, B.right));
    }

3、 二叉树的镜像

3.1 题目描述:

请完成一个函数,输入一个二叉树,该函数输出它的镜像。

3.2 题解
3.2.1递归
    public TreeNode mirrorTree(TreeNode root) {
        if(root==null)
            return root;
        mirror(root);
        return root;
    }

    /**
     * 当遍历到了树的叶子节点之后,返回
     * 将每个节点的左右子节点调换位置
     * 在对每个节点的左右子节点进行同样的操作
     * @param root
     */
    public void mirror(TreeNode root){
        if(root==null)
            return;
        TreeNode temp=root.left;
        root.left=root.right;
        root.right=temp;
        mirror(root.left);
        mirror(root.right);
    }
3.2.2 更优递归
 public TreeNode mirrorTree(TreeNode root) {
        if(root == null) return null;
        TreeNode tmp = root.left;
        root.left = mirrorTree(root.right);
        root.right = mirrorTree(tmp);
        return root;
    }
3.2.3 辅助栈(或队列)
 public TreeNode mirrorTree(TreeNode root) {
        if(root == null) return null;
        Stack<TreeNode> stack = new Stack<>() {{ add(root); }};
        while(!stack.isEmpty()) {
            TreeNode node = stack.pop();
            if(node.left != null) stack.add(node.left);
            if(node.right != null) stack.add(node.right);
            TreeNode tmp = node.left;
            node.left = node.right;
            node.right = tmp;
        }
        return root;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值