LeetCode算法題——最長同值路徑

        int max = 0;   //保存當前最長路徑值

        public int LongestUnivaluePath(TreeNode root)
        {
            if (root == null) return 0;
            else
            {
                GetLongest(root);
            }
            return max;
        }

        public int GetLongest(TreeNode root)
        {
            int l = root.left != null ? GetLongest(root.left) : 0;    //遞歸查找它的所有路徑並且得到之前的路徑值
            int r = root.right != null ? GetLongest(root.right) : 0;
            int resl = (root.left != null && root.val == root.left.val) ? l + 1 : 0;   //判斷路徑點相同就+1否則爲0
            int resr = (root.right != null && root.val == root.right.val) ? r + 1 : 0;
            //如果和大於max就更新max, 因爲都是對root做判斷, 所以resl和resr都是對同一個路徑點的長度做判斷, 因此相加纔得到當前路徑點的長度
            max = Math.Max(max, resl + resr);   
            return Math.Max(resl, resr);
        }

 public class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;
        public TreeNode(int x) {
            val = x;
        }
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章