LeetCode-Lowest Common Ancestor of a Binary Tree
阿新 • • 發佈:2018-11-11
一、Description
題目描述:給定一個二叉樹和兩個結點p和q,找出p和q的最近公共祖先。
二、Analyzation
通過遍歷分別找到從根節點到p和q的路徑,放入一個棧中。如果兩個棧的大小相同,則同時出棧直到兩個棧出棧的結點值相同,則為最近公共祖先,如果兩個棧的大小不同(p和q不在同一層),則大的那個棧出棧直到和另一個棧的大小相同,然後一起出棧直到結點值相同。
三、Accepted code
class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == null || p == null || q == null) { return null; } Stack<TreeNode> stack1 = new Stack<>(); Stack<TreeNode> stack2 = new Stack<>(); help(root, p, stack1); help(root, q, stack2); if (stack1.size() > stack2.size()) { while (stack1.size() != stack2.size()) { stack1.pop(); } } else if (stack1.size() < stack2.size()) { while (stack1.size() != stack2.size()) { stack2.pop(); } } while (!stack1.isEmpty() && !stack2.isEmpty()) { if (stack1.peek().val == stack2.peek().val) { return stack1.peek(); } stack1.pop(); stack2.pop(); } return null; } public boolean help(TreeNode root, TreeNode node, Stack<TreeNode> stack) { stack.add(root); if (root.val == node.val) { return true; } boolean find = false; if (root.left != null) { find = help(root.left, node, stack); } if (root.right != null && !find) { find = help(root.right, node, stack); } if (!find) { stack.pop(); } return find; } }