标签:更新 面试 root 返回值 后序遍历 程序员 方法 amp rgs
法一:后序遍历。搞清返回值逻辑。
更新别的方法
public class Parent {
public static void main(String args[]) {
Node n1=new Node(1);
Node n2=new Node(2);
Node n3=new Node(3);
Node n4=new Node(4);
n1.left=n2;
n1.right=n3;
n3.left=n4;
System.out.print(firstParent(n1,n3,n4).val);
}
public static Node firstParent(Node root,Node node1,Node node2) {
if(root==null||root==node1||root==node2) {
return root;
}
Node leftNode=firstParent(root.left,node1,node2);
Node rightNode=firstParent(root.right,node1,node2);
if(leftNode!=null&&rightNode!=null) {
return root;
}
if(leftNode==null&&rightNode==null) {
return null;
}
else {
return leftNode!=null?leftNode:rightNode;
}
}
}
[程序员代码面试指南]二叉树问题-找到二叉树中两节点最近公共祖先
标签:更新 面试 root 返回值 后序遍历 程序员 方法 amp rgs
原文地址:https://www.cnblogs.com/coding-gaga/p/11013646.html