码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode235

时间:2017-04-20 15:25:28      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:private   结束   amp   tle   mon   http   class   tco   oid   

/**
 * 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 {
    Stack<TreeNode> SP = new Stack<TreeNode>();
        Stack<TreeNode> SQ = new Stack<TreeNode>();

        bool findP = false;//是否找到p
        bool findQ = false;//是否找到q

        List<TreeNode> listP = new List<TreeNode>();
        List<TreeNode> listQ = new List<TreeNode>();

        private void DFS(TreeNode root, int p, int q)
        {
            if (root != null)
            {
                if (findP && findQ)
                {
                    return;
                }

                if (!findP)
                {
                    SP.Push(root);
                }
                if (!findQ)
                {
                    SQ.Push(root);
                }

                if (root.val == p)
                {
                    //p结点寻找结束
                    findP = true;
                    listP = SP.ToList();
                }
                if (root.val == q)
                {
                    //q结点寻找结束
                    findQ = true;
                    listQ = SQ.ToList();
                }

                if (root.left != null)
                {
                    DFS(root.left, p, q);
                }
                if (root.right != null)
                {
                    DFS(root.right, p, q);
                }

                if (!findP)
                {
                    SP.Pop();
                }
                if (!findQ)
                {
                    SQ.Pop();
                }
            }
        }

        public TreeNode LowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q)
        {
            if (root == null || p == null || q == null)
            {
                return null;
            }
            //采用深度优先搜索,找到p和q
            DFS(root, p.val, q.val);

            for (int i = 0; i < listP.Count; i++)
            {
                for (int j = 0; j < listQ.Count; j++)
                {
                    var nodep = listP[i];
                    var nodeq = listQ[j];
                    if (nodep.val == nodeq.val)
                    {
                        return nodep;
                    }
                }
            }
            return null;
        }
}

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/#/description

leetcode235

标签:private   结束   amp   tle   mon   http   class   tco   oid   

原文地址:http://www.cnblogs.com/asenyang/p/6738867.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!