【剑指offer系列】-08二叉树的下一个节点(哈希)

本题的思想,非递归中序遍历

使用map存每个节点的父节点
一个节点的下一个节点:
1)如果当前节点有右子树,则下一节点为右子树的最左节点
2)如果当前节点没有右子树,则下一个节点为当前节点的最小长辈(父、爷、祖父、曾祖父—)节点.left == 当前节点
如果当前节点的长辈节点们,都遍历到root的长辈null了,都没有.left == 当前节点的。则说明下一个节点为null

public class MidTree2 {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(1);
        TreeNode n1 = new TreeNode(2);
        TreeNode n2 = new TreeNode(3);
        root.right = n1;
        n1.left = n2;
        List<Integer> midRes = midTreeNotRecursion(root);
        System.out.println(midRes);
    }

    public static List<Integer> midTreeNotRecursion(TreeNode root) {
        List<Integer> list = Lists.newArrayList();
        if (root == null) {
            return list;
        }
        if (root.left == null && root.right == null) {
            list.add(root.val);
            return list;
        }

        TreeNode temp = root;
        Map<TreeNode, TreeNode> curAndParentMap = new HashMap<>();
        curAndParentMap.put(root, null);
        while (temp.left != null) {
            curAndParentMap.put(temp.left, temp);
            temp = temp.left;
        }

        // 1.初始节点
        list.add(temp.val);
        TreeNode curTreeNode = temp;

        // 2.添加节点
        while (true) {
            TreeNode nextTreeNode = next(curAndParentMap, curTreeNode);
            if (nextTreeNode == null) {
                break;
            }
            list.add(nextTreeNode.val);
            curTreeNode = nextTreeNode;
        }
        return list;
    }

    private static TreeNode next(Map<TreeNode, TreeNode> curAndParentMap, TreeNode curTreeNode) {
        TreeNode next;
        if (curTreeNode.right == null) {
            TreeNode parent = curAndParentMap.get(curTreeNode);
            while (true) {
                if (parent == null) {
                    return null;
                } else if (parent.left != null && Objects.equals(parent.left.val, curTreeNode.val)) {
                    return parent;
                } else {
                    curTreeNode = parent;
                    parent = curAndParentMap.get(curTreeNode);
                }
            }
        } else {
            next = curTreeNode.right;
            curAndParentMap.put(next, curTreeNode);

            while (next.left != null) {
                curAndParentMap.put(next.left, next);
                next = next.left;
            }
        }
        return next;
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值