class Solution(object): def longestPath(self, root): if root == None: return 0 left = self.recursive(root.left, root.val, 1) right = self.recursive(root.right, root.val, 1) return max(left, 1, right) def recursive(self, node, preVal, tempLength): if node == None: return 0 thisLength = tempLength + 1 if node.val == preVal + 1 else 1 left = self.recursive(node.left, node.val, thisLength) right = self.recursive(node.right, node.val, thisLength) return max(left, thisLength, right) class Solution(object): def longestPath(self, root): if root == None: return 0 left, Lbig, Lsmall= self.recursive(root.left, root.val) right, Rbig, Rsmall = self.recursive(root.right, root.val) thisLength = max(left, right, Lbig+1+Rsmall, Rbig+1+Lsmall) return thisLength def recursive(self, node, preVal): if root == None: return 0, 0, 0 left, Lbig, Lsmall = self.recursive(root.left, root.val) right, Rbig, Rsmall = self.recursive(root.right, root.val) thisLength = max(left, right, Lbig+1+Rsmall, Rbig+1+Lsmall) if root.val == preVal + 1: return thisLength, max(Lbig, Rbig)+1, 0 elif root.val == preVal - 1: return thisLength, 0, max(Lsmall, Rsmall)+1 else: return thisLength, 0, 0
|