码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树的最近公共祖先--递归解法

时间:2021-02-17 14:40:10      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:stc   static   mamicode   border   tab   comm   ===   ide   ||   

 

来源: https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/solution/er-cha-shu-de-zui-jin-gong-gong-zu-xian-by-leetc-2/

信息分类: IT/算法

目标用户: 程序员/java

相关知识点:二叉树、递归

 

算法关键源码解析:

技术图片

 

 

 

 

如下图,是构造的一颗二叉树,现在需要找出节点N7,节点N8的最近公共祖先。

 

                  3
     5             1
6        2      0      8
      7     4

 

以上算法中采用的是递归算法,递归算法写起来代码简洁,但没那么直观,理解起来比较费劲,下面用对具体的代码块进行了标号,

如下嵌套表展现代码的执行过程,有助有帮助大家理解递归的执行过程。

 

 技术图片

 

 

 

1

N3

2

T

1

N5

2

F

1

N6

2

F

1

NULL

2

-

3

-

4

-

5

-

 

3

F

1

NULL

2

-

3

-

4

-

5

-

 

4

-

5

F

 

3

T

2

T

1

N7

2

1

NULL

2

-

3

-

4

-

5

-

 

3

1

NULL

2

-

3

-

4

-

5

-

 

4

-

5

T

 

3

F

1

N4

 ...

..

 

4

-

5

T

 

4

-

5

T

 

3

T

1

N1

..

..

 

4

T  终极答案

5

--

 

 

 

完整源码:


class Solution {

    private TreeNode ans;

    public Solution() {
        this.ans = null;
    }

    private boolean dfs(TreeNode root, TreeNode p, TreeNode q) {
        System.out.println("节点:" + root);
        if (root == null) {
            System.out.println("=====:null==>" + false);
            return false;
        }
        boolean lson = dfs(root.left, p, q);
        boolean rson = dfs(root.right, p, q);
        if ((lson && rson) || ((root.val == p.val || root.val == q.val) && (lson || rson))) {
            ans = root;
        }
        boolean b=lson || rson || (root.val == p.val || root.val == q.val);
        System.out.println("=====:"+root+ "==>" + b);
        return b;
    }

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        this.dfs(root, p, q);
        return this.ans;
    }

    public static void main(String[] args) {
        TreeNode n1 = new TreeNode(3, 5, 1);
        n1.left.left = new TreeNode(6);
        n1.left.right = new TreeNode(2, 7, 4);
        n1.right = new TreeNode(1, 0, 8);

        TreeNode n = new Solution().lowestCommonAncestor(n1, new TreeNode(8), new TreeNode(7));
        System.out.println(n);
    }

}

class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;

    public TreeNode(int val) {
        this.val = val;
    }

    public TreeNode(int val, int left, int right) {
        TreeNode l = new TreeNode(left);
        TreeNode r = new TreeNode(right);
        this.val = val;
        this.left = l;
        this.right = r;
    }

    @Override
    public String toString() {
        return "" + this.val;
    }
}

 

  

二叉树的最近公共祖先--递归解法

标签:stc   static   mamicode   border   tab   comm   ===   ide   ||   

原文地址:https://www.cnblogs.com/kevin7234/p/14402255.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!