返回的值为找没找到, 如果找到了就返回这个节点
先序和后续的结合
前序部分定义找没找到数 找到就返回该节点
后续部分用于判断找到的结果
如果当前的节点返回一侧为空,说明该部分没有找到,
则返回当前节点 因为是后序遍历 所以会返回最先找到的节点。
public class Solution {
/**
*
* @param root TreeNode类
* @param o1 int整型
* @param o2 int整型
* @return int整型
*/
public int lowestCommonAncestor (TreeNode root, int p, int q) {
TreeNode res = LCA(root,p,q);
return res.val;
}
public TreeNode LCA(TreeNode root, int p, int q){
if(root ==null) return null;
if(root.val == p || root.val == q) return root;
TreeNode a = LCA(root.left,p,q);
TreeNode b = LCA(root.right,p,q);
if(a == null) return b;
else if (b == null) return a;
else return root;
}
}


京公网安备 11010502036488号