Microsoft Interview: In binary tree, find two nodes' nearest common father
来源:互联网 发布:农村人口老龄化数据 编辑:程序博客网 时间:2024/06/15 16:05
题目
二叉树中,找到任意两个节点最近的公共父节点。(微软onsite第三轮面试题)
思路
1 看到二叉树,总是从递归的方式开始想。
2 大多数题型,都是从深度遍历/广度遍历 转换而来,这道题目也不例外。
3 一次遍历完成不了?那么试着分开遍历。只要记录一个数到根节点的路径,再对记录进行操作就可以完成了。
4 用什么来记录?stack还是queue,根据代码的逻辑来。
5 如果是二叉查找树,可以简化方法。
代码
public static TreeNode findCommonFatherNode(TreeNode root, int i, int j) {LinkedList<TreeNode> stack1 =new LinkedList<>();LinkedList<TreeNode> stack2 =new LinkedList<>();recordPath(root,i,stack1);recordPath(root,j,stack2);TreeNode answer = root;while(!stack1.isEmpty()&&!stack2.isEmpty()){TreeNode cur1 = stack1.pop();TreeNode cur2 = stack2.pop();if(cur1 != cur2){break;}answer = cur1;}return answer;}private static boolean recordPath(TreeNode root,int val,LinkedList<TreeNode> stack){if(root == null ){return false;}if(root.val == val){stack.push(root);return true;}if(recordPath(root.left,val,stack)){stack.push(root);return true;}else if(recordPath(root.right,val,stack)){stack.push(root);return true;}return false;}
0 0
- Microsoft Interview: In binary tree, find two nodes' nearest common father
- Find the nearest common ancestor of any two nodes in a binary search tree
- Find the common ancestor of two nodes in a binary tree
- find distance between two nodes in a binary tree
- Lowest Common Ancestor of The Two Nodes in a Binary Tree
- [CTCI] 4.6 First Common Ancestor for Two Nodes On a Binary tree
- Binary search (4) -- Find Right Interval,Count Complete Tree Nodes,Divide Two Integers
- ch4.6: find the LCA of 2 nodes in a binary tree with 3 different methods
- Lowest Common Ancestor (LCA) of two nodes in graph
- Lowest common ancestor in binary search tree
- Least Common Ancestor in a Binary Tree
- 【Leetcode】Lowest common treenode in binary tree
- Lowest Common Ancestor in a Binary Tree
- binary search tree interview
- [Leetcode] Binary tree -- 501. Find Mode in Binary Search Tree
- 【Leetcode】501. Find Mode in Binary Tree
- 501. Find Mode in Binary Search Tree
- 501. Find Mode in Binary Search Tree
- zoj 1025 Wooden Sticks
- noip 2011 选择客栈
- java垃圾回收算法
- 1.8 C语言的文件系统
- WINCE--流设备驱动简介及往BSP添加
- Microsoft Interview: In binary tree, find two nodes' nearest common father
- 最小堆实现
- 2.3-删除链表中间节点
- 山东省2013高职分数线
- 进程与线程的一个简单解释
- 用Java Serialization实现任意文件网络传输
- 判断对象在堆上的代码例子
- Java实现线性表
- UVA10650 - Determinate Prime - 数论