二叉树

LCA问题

给一个 二叉树 , 求最深节点的最小公共父节点。

//贴个自己的code.用的是level traversal,找出最深层的head和tail节点,用一个map来track 节点到父节点的映射。
//如果head 和tail相等,说明最深层就一个节点,如果不等,分别从map里向parent节点搜索,知道发现一个//公共的节点即为LCA。
public int lcaBFS(TreeNode root) {
                if(root == null)        return -1;
                // <node -> parent node>
                Map<TreeNode, TreeNode> map = new HashMap<TreeNode, TreeNode>();

                TreeNode head = null, tail = null;  // the head and tail node in a level
                Queue<TreeNode> que = new LinkedList<TreeNode>();
                que.offer(root);
                map.put(root, null);
                while(!que.isEmpty()) {
                        head = null; tail = null;
                        int sz = que.size();
                        while(sz-- > 0) {
                                TreeNode curr = que.poll();
                                if(head == null)        head = curr;
                                if(sz == 0)        tail = curr;
                                if(curr.left != null) {
                                        map.put(curr.left, curr);
                                        que.offer(curr.left);
                                }
                                if(curr.right != null) {
                                        map.put(curr.right, curr);
                                        que.offer(curr.right);
                                }
                        }
                }

                while(head != tail){
                        head = map.get(head);
                        tail = map.get(tail);
                }
                return head.val;
        }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值