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

 

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