LeetCode-236 二叉树最近公共祖先

LeetCode-236 二叉树最近公共祖先

/*	236. 二叉树的最近公共祖先
 * 	题目描述:给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
 * 	解体思路:分两部分解决
 * 			  第一部分:实现判断两个结点包含于某根节点的子树内
 *     		  第二部分:先序遍历二叉树,如果根节点的子树包含qp目标结点
 *     				    传入左孩子,进行递归。传入右孩子,进行递归。
 *     				    如果孩子的递归返回值为null,则返回根节点,如果孩子的递归结果非空则返回孩子。
 * 			          
 * */
public class LowestCommonAncestorOfABinaryTree {
	public static void main(String[] args) {
		TreeNode root = new TreeNode(1);
		root.left = new TreeNode(2);
		root.right = new TreeNode(3);
		root.left.left = new TreeNode(4);
		root.left.right = new TreeNode(5);
		TreeNode p = new TreeNode(4);
		TreeNode q = new TreeNode(5);
		LowestCommonAncestorOfABinaryTreeSolution solution = new LowestCommonAncestorOfABinaryTreeSolution();
		System.out.println(solution.lowestCommonAncestor(root, p, q).val);
	}
}

class LowestCommonAncestorOfABinaryTreeSolution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root==null) return null;
        TreeNode result = nodesInTree(root, p, q);
        if(result!=null) {
        	TreeNode left = lowestCommonAncestor(root.left, p, q);
        	TreeNode right = lowestCommonAncestor(root.right, p, q);
        	if(left!=null) return left;
        	if(right!=null) return right;
        }
        return result;
    }
    
    public TreeNode nodesInTree(TreeNode root, TreeNode p, TreeNode q) {
    	Stack stack = new Stack();
    	boolean p_tag = false;
    	boolean q_tag = false;
    	stack.push(root);
    	while(!stack.isEmpty()) {
    		TreeNode node = stack.pop();
    		if(node.val==p.val) p_tag=true;
    		if(node.val==q.val) q_tag=true;
    		if(node.left!=null) stack.push(node.left);
    		if(node.right!=null) stack.push(node.right);
    	}
    	if (p_tag&&q_tag) return root;
    	return null;
    }
}

 

你可能感兴趣的:(LeetCode)