1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public class Solution { TreeNode result = null; public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { findResult(root, p, q, new boolean[2]); return result; } private void findResult(TreeNode root, TreeNode p, TreeNode q, boolean[]p_q){ if (root == null) return; boolean forLeft[] = new boolean[2]; boolean forRight[] = new boolean[2]; if (result == null) findResult (root.left, p, q, forLeft); if (result == null) findResult (root.right, p, q, forRight); p_q[0] |= (root == p) || forLeft[0] || forRight[0]; p_q[1] |= (root == q) || forRight[1] || forLeft[1]; if (p_q[0] && p_q[1] && result == null) result = root; return; } } |
Monday, November 2, 2015
[leetcode]Lowest Common Ancestor of a Binary Tree
这题仔细点把base case写好就好了。
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment