首页 > 代码库 > CC150 4.6
CC150 4.6
4.6 Design an algorithm and write code to find the first common ancestor of two nodes in a binary tree. Avoid storing additional nodes in a data structure. NOTE: This is not necessarily a binary search tree.
BT
Node find(Node n, Node a, Node b) { if (n == a || n == b) { return n; } int nodeMatch = nodeMatch(a.left); if (nodeMatch == 0) return find(n.right, a, b); else if (nodeMatch == 1) return n; else return find(r.left, a, b); } int nodeMatch(Node n, Node a, Node b) { if (n == null) return 0; int toReturn = 0; if (n == a || n == b) toReturn ++; toReturn += find(n.left) + find(n.right); }
CC150 4.6
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。