博客
关于我
剑指offer--树--树中两个结点的最低公共祖先
阅读量:135 次
发布时间:2019-02-26

本文共 2510 字,大约阅读时间需要 8 分钟。

???????????????????????????????

  • ??????????????????????????????????????DFS???????
  • ??????????????????????????????????????????????
  • ??????????????

    import java.util.ArrayList;import java.util.Stack;public class Test2 {    public static void main(String[] args) {        // ????        TreeNode root = new TreeNode(6);        TreeNode left = new TreeNode(2);        left.left = new TreeNode(0);        left.right = new TreeNode(4);        left.right.left = new TreeNode(7);        left.right.right = new TreeNode(9);        root.left = left;        TreeNode right = new TreeNode(8);        right.left = new TreeNode(3);        right.left.right = new TreeNode(5);        root.right = right;        System.out.println(lowestCommonAncestorII(root, left, right));    }    public static TreeNode lowestCommonAncestorII(TreeNode root, TreeNode p, TreeNode q) {        List
    pPath = findPath(root, p); List
    qPath = findPath(root, q); // ??????????null if (pPath == null || qPath == null) { return null; } // ??????????????? int minLength = Math.min(pPath.size(), qPath.size()); TreeNode common = null; for (int i = 0; i < minLength; i++) { if (pPath.get(i) == qPath.get(i)) { common = pPath.get(i); } else { break; } } return common; } private static List
    findPath(TreeNode root, TreeNode target) { List
    path = new ArrayList<>(); Stack
    stack = new Stack<>(); stack.push(root); while (!stack.isEmpty()) { TreeNode node = stack.pop(); if (node == target) { // ????????????path? while (!stack.isEmpty()) { path.add(stack.pop()); } return path; } if (node.left != null) { stack.push(node.left); } if (node.right != null) { stack.push(node.right); } } return null; }}

    ????

  • findPath ???

    • ?????????????DFS?????????????????
    • ???????????????????????????????????
  • lowestCommonAncestorII ???

    • ?? findPath ??????????p?q????
    • ?????????????????????
    • ?????????????????????????????????????
  • ??????

    • main ???????????? lowestCommonAncestorII ???????????
    • lowestCommonAncestorII ?????????????????????????????
    • findPath ????????DFS?????????

    ????????????O(n)???????????????????????????????

    转载地址:http://tnzu.baihongyu.com/

    你可能感兴趣的文章
    PC端编辑 但能在PC端模拟移动端预览的富文本编辑器
    查看>>
    PDB文件:每个开发人员都必须知道的
    查看>>
    springMVC学习(二)
    查看>>
    Pdfkit页眉和页脚
    查看>>
    PDF中的Pandoc语法突出显示不起作用
    查看>>
    pdf从结构新建书签_在PDF文件中怎样创建书签
    查看>>
    pdf做成翻页电子书_第一弹:常见BOOX电子书阅读器问题解答,这些技能你都会吗?...
    查看>>
    PDF工具箱-分割提取合并
    查看>>
    pdf打印骑缝章
    查看>>
    PDF文字识/编辑?这个工具真的很强大!
    查看>>
    pdf文档出现乱码如何修改
    查看>>
    pdf根据模板导出
    查看>>
    PDF调出本来存在的书签面板
    查看>>
    pdf转图片
    查看>>
    pdf转图片、提取pdf文本、提取pdf图片
    查看>>
    springMvc 3.0 使用基本原理
    查看>>
    springCloud整合RabbitMQ实现消息中间件
    查看>>
    pdo sqlserver
    查看>>
    SpringCloud实战(十一)-更优的分布式配置解决方案(Apollo)
    查看>>
    PDO中捕获SQL语句中的错误
    查看>>