Java日记2018-06-05

2018-06-05  本文已影响0人  hayes0420
  1. 二叉树中和为某一值的路径

递归的实现,栈弹入弹出的时机选择还蛮妙,测试数据时候猜测+试验出来,理解了一下结果

//二叉树中和为某一值的路径
    public static void findpath(TreeNode root, int target) {
        if (root == null)
            return;
        Stack<Integer> path = new Stack<Integer>();
        findpathcore(root, target, path);
    }

    public static void findpathcore(TreeNode root, int target, Stack<Integer> path) {
        if (root == null)
            return;
        //注意push即pop的位置,要在判断外边,这样弹出时候能弹出到最外层,蛮抽象,再看时候可能会更理解……
        path.push(root.val);
        if (root.left == null && root.right == null) {
            if (target == root.val) {
                //path.push(root.val);
                for (int i : path) {
                    System.out.print(i + " ");
                }
                System.out.println(" ");
            }
        } else {
            //path.push(root.val);
            findpathcore(root.left, target - root.val, path);
            findpathcore(root.right, target - root.val, path);
            //path.pop();
        }
        path.pop();
    }
  1. 复杂链表的复制

方法还是赋值拆分的老路
直接用题解的方法,主要看看下次能不能更快速想到这个方法

public RandomListNode Clone(RandomListNode pHead) {
    if (pHead == null)
        return null;
    // 插入新节点
    RandomListNode cur = pHead;
    while (cur != null) {
        RandomListNode clone = new RandomListNode(cur.label);
        clone.next = cur.next;
        cur.next = clone;
        cur = clone.next;
    }
    // 建立 random 链接
    cur = pHead;
    while (cur != null) {
        RandomListNode clone = cur.next;
        if (cur.random != null)
            clone.random = cur.random.next;
        cur = clone.next;
    }
    // 拆分
    cur = pHead;
    RandomListNode pCloneHead = pHead.next;
    while (cur.next != null) {
        RandomListNode next = cur.next;
        cur.next = next.next;
        cur = next;
    }
    return pCloneHead;
}
  1. 二叉搜索树与双向链表

原来的做法是错误的,需要重新审视

private TreeNode pre = null;
    private TreeNode head = null;

    public TreeNode Convert(TreeNode root) {
        if (root == null)
            return null;
        inOrder(root);
        return head;
    }

    private void inOrder(TreeNode node) {
        if (node == null)
            return;
        inOrder(node.left);
        node.left = pre;
        if (pre != null)
            pre.right = node;
        pre = node;
        if (head == null)
            head = node;
        inOrder(node.right);
    }
上一篇下一篇

猜你喜欢

热点阅读