美文网首页
236. 二叉树的最近公共祖先

236. 二叉树的最近公共祖先

作者: Andysys | 来源:发表于2019-12-30 22:25 被阅读0次
        private TreeNode ans = null;
    
        public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            recurseTreeNode(root, p, q);
            return ans;
        }
    
        private boolean recurseTreeNode(TreeNode current, TreeNode p, TreeNode q) {
            if (current == null) {
                return false;
            }
    
            int left = recurseTreeNode(current.left, p, q) ? 1 : 0;
            int right = recurseTreeNode(current.right, p, q) ? 1: 0;
            int mid = (current == p || current == q) ? 1 : 0;
    
            int sum = left + right + mid;
            if (sum >= 2) {
                ans = current;
            }
            return sum > 0;
        }
    

    相关文章

      网友评论

          本文标题:236. 二叉树的最近公共祖先

          本文链接:https://www.haomeiwen.com/subject/wzbeoctx.html