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
原创粉丝点击