标签:
题目描述:/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int x) { val = x; } * } */ public class Solution { public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { var pathP = new List<TreeNode>(); Path(root, p, pathP); var pathQ = new List<TreeNode>(); Path(root, q , pathQ); var i = 0; while(i < pathP.Count || i < pathQ.Count){ if(i >= pathP.Count ||i >= pathQ.Count){ return pathP[--i]; } if(pathP[i].val == pathQ[i].val){ i ++; } else{ return pathP[--i]; } } return null; } public void Path(TreeNode node, TreeNode n, IList<TreeNode> list){ if(node == null){ return ; } list.Add(node); if(n.val == node.val){ return; } if(n.val < node.val){ Path(node.left, n ,list); } else{ Path(node.right, n ,list); } } }
Leetcode--Lowest Common Ancestor of a Binary Search Tree
标签:
原文地址:http://blog.csdn.net/lan_liang/article/details/50145263