def _dfs_invert(node: TreeNode): if node.left and node.right: node.left, node.right = node.right, node.left elif node.left and not node.right: node.right, node.left = node.left, None elif node.right and not node.left: node.left, node.right = node.right, None if node.left: _dfs_invert(node.left) if node.right: _dfs_invert(node.right)
# @Date : 2019/5/21 14:59 # @Author: hlliu from queue import LifoQueue from models.binary_tree import TreeNode class Solution: def preorderTraversal(self, root: TreeNode): res = [] stack = LifoQueue() cur = root while cur is not None or not stack.empty(): if cur is not None: stack.put(cur) res.append(cur.val) cur = cur.left else: cur = stack.get().right return res root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.left.left = TreeNode(4) root.left.right = TreeNode(5) s = Solution() print(s.preorderTraversal(root))
from pathlib import Path import sys sys.path.append(str(Path(__file__).parent.parent.absolute())) from models.binary_tree import TreeNode, arr_to_node class Solution: def isSameTree(self, p: TreeNode, q: TreeNode) -> bool: while p != None or q != None: if p == None or q == None or (p.val != q.val): return False else: if not self.isSameTree(p.left, q.left): return False if not self.isSameTree(p.right, q.right): return False return True return True s = Solution() p = TreeNode(1) p.left = TreeNode(2) p.right = TreeNode(3) q = TreeNode(1) q.left = TreeNode(2) result = s.isSameTree(p, q) print(result)