LeetCode-Lowest Common Ancestor of a Binary Tree

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Apple_hzc/article/details/83718692

一、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;
    }
}

猜你喜欢

转载自blog.csdn.net/Apple_hzc/article/details/83718692
今日推荐