题解 | 实现二叉树先序,中序和后序遍历
实现二叉树先序,中序和后序遍历
https://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362
# def __init__(self, x): # self.val = x # self.left = None # self.right = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param root TreeNode类 the root of binary tree # @return int整型二维数组 # class Solution: def threeOrders(self , root: TreeNode) -> List[List[int]]: # write code here # 将前中后序遍历同时进行 # 因为前中后序遍历只有根节点的顺序在不同的位置 # 而根节点的放置并不影响递归过程 self.result = [[],[],[]] self.order(root) return self.result def order(self,root:TreeNode): if not root: return self.result[0].append(root.val) self.order(root.left) self.result[1].append(root.val) self.order(root.right) self.result[2].append(root.val) # 这是借鉴热门答案自己理解后写的代码 # 这里我们学到了: # 在一个类里的函数,可以相互调用,不分先后 # 这里的order函数在threeorders后面,但在threeorders函数中仍然调用了 # 同时在定义类中的函数时,函数内的变量也可以相互调用 # 这里的result变量是在threeorders函数中定义的,但在order中直接使用了