zoukankan      html  css  js  c++  java
  • [leetCode]236. 二叉树的最近公共祖先

    递归

    思路:
    直观的想法是从底向上遍历,如果发现p在当前节点左子树q在当前节点右子树或者p在当前节点右子树,q在当前节点左子树时则说明当前节点是p与q的最小公共祖先。
    二叉树的后序遍历正好符合自底向上的遍历条件,因此使用后序遍历。这题由于要使用回溯所以返回值不能为空

    class Solution {
        public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            // root为null代表没有发现p与q节点,反之为发现了pq节点
            if (root == p || root == q || root == null) return root;
            TreeNode left = lowestCommonAncestor(root.left, p, q);
            TreeNode right = lowestCommonAncestor(root.right, p, q);
            if (left != null && right != null) return root;
            else if (left == null && right != null) return right;
            else if (left != null && right == null) return left;
            else return null;
        }
    }
    
  • 相关阅读:
    Code review
    一点心得
    有关双向追踪性的一点感觉
    测试用例分析的一点心得
    js简单的抽屉菜单
    新的感受
    linux的VPS如何分区
    PHP中Unicode转码和解码的实现
    xampp安装及配置
    js Unicode编码转换
  • 原文地址:https://www.cnblogs.com/PythonFCG/p/13921133.html
Copyright © 2011-2022 走看看