当前位置 : 主页 > 手机开发 > harmonyos >

leetcode-236-Lowest Common Ancestor of a Binary Tree

来源:互联网 收集:自由互联 发布时间:2023-08-26
Error: cannot solve it, use the tree solving pattern: end_condition/base cases;do_something_for_root;left = func(root-left);right = func(root-right);return something; In here, for lca(root, p, q), we first have ending/base case: if(root ==


Error:
cannot solve it, use the tree solving pattern:

end_condition/base cases;
do_something_for_root;
left = func(root->left);
right = func(root->right);
return something;

In here, for lca(root, p, q), we first have ending/base case:

if(root == q)
	return q;
if(root == p)
	return q;
if(root == null)
	return null;

For first two cases, it means that in lca(root, p, q), we found one of node, and for the other root, either it is not within the root(i.e. equal to null) or in the left/right subtree. In both case we can know the lca is the one we found so far.

The last case means we cannot found any of them, return null.

For recursion:

left = lca(root.left, p, q);
right = lca(root.right, p, q);

if(left != null && right != null)
	return root;
else if(left != null)
	return left;
else if(right != null)
	return right;
else
	return null;

It is easy to understand, I will not explain it.


【文章出处:抗攻击防御ddos http://www.558idc.com/krgf.html 复制请保留原URL】
上一篇:leetcode-286-Walls and Gates
下一篇:没有了
网友评论