CSDN_FlyYoung的博客

个人学习总结,望指教!

循环二叉树(去哪儿2017校招真题)

题目描述

循环二叉树(去哪儿2017校招真题)

思路分析

使用一个map存放关联的父子节点(key:子节点,value:父节点),key & value初始化为node1节点
使用一个Node类型对象作为父节点,对每一步,进行如下操作:
    若向左走并且左子节点不为空,则将左子节点及其父节点放入map,更新父节点p为其左子节点;
    若向右走并且右子节点不为空,则将右子节点及其父节点放入map,更新父节点p为其右子节点;
    若回退并且父节点不为空,更新父节点p为其父节点 
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

class Node {
    public int v;
    public Node left;
    public Node right;
}

class Tree {
    public Node node1;
    public Node node2;
    public Node node3;
    public Node node4;
    public Node node5;

    public Tree() {
        node1 = new Node();
        node2 = new Node();
        node3 = new Node();
        node4 = new Node();
        node5 = new Node();

        node1.v = 1;
        node1.left = node2;
        node1.right = node3;

        node2.v = 2;
        node2.left = node3;
        node2.right = node4;

        node3.v = 3;
        node3.left = node4;
        node3.right = node5;

        node4.v = 4;
        node4.left = node5;
        node4.right = node1;

        node5.v = 5;
        node5.left = node1;
        node5.right = node2;

    }
}

public class Main {
    @SuppressWarnings("resource")
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String str = null;

        while (sc.hasNext()) {
            str = sc.nextLine();

            // 存放关联的父子节点的map
            Map<Node, Node> map = new HashMap<Node, Node>();
            Tree tree = new Tree();
            map.put(tree.node1, tree.node1);

            // 父节点
            Node p = tree.node1;    

            for (int i = 0; i < str.length(); i++) {
                // 向左走
                if (str.charAt(i) == 'L') {
                    if (p.left != null) {
                        map.put(p.left, p);
                        p = p.left;
                    }
                }

                // 向右走
                if (str.charAt(i) == 'R') {
                    if (p.right != null) {
                        map.put(p.right, p);
                        p = p.right;
                    }
                }

                // 回退
                if (str.charAt(i) == 'B') {
                    if (map.get(p) != null) p = map.get(p);
                }
            }
            System.out.println(p.v);
        }
    }
}
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/CSDN_FlyYoung/article/details/77970603
文章标签: 去哪儿 二叉树
个人分类: 刷题-未实现题目
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭