Challenge: Find the problems in the answer below:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
if root is None:
return
leftPath = self.binaryTreePaths(root.left)
rightPath = self.binaryTreePaths(root.right)
if leftPath is None and rightPath is None:
return [f"{root.val}"]
elif leftPath is None:
Paths = rightPath
elif rightPath is None:
Paths = leftPath
else:
Paths = leftPath + rightPath
for path in Paths:
path = f"{root.val}" + "->" + path
return Pathsthe most critical:
for path in Paths:
path = f"{root.val}" + "->" + pathit equals to C below:
typedef struct {
int val;
// ... others
} Node;
// 2. nodes is Node**
Node* nodes[] = { ptr_to_node1, ptr_to_node2, ptr_to_node3 };
int length = 3;
for (int i = 0; i < length; i++) {
// create a local pointer variable node( the name we wrote), then copy the elements in the list to the node
Node* node = nodes[i];
node.val = 10
// equals to:
// node->val = 10; in C, you succeed!
// node = some_other_node
// equals to node = ptr_to_another_one; in C
}this is a trap of
for node in nodes
we can use these method to actually get nodes[i] and modify it:
write nodes[i] directly
use list comprehension
return [str(root.val) + "->" + path for path in Paths]for i in len(nodes):
nodes[i] = None + list is invaild, so return a [], not None
You may be mislead by Falsy
these value will be recognized as False after if while bool():
empty list[], set(), None, 0, False, "", {}, ().
but only after if while bool()! When they must be casted to True or False
Difference between is and ==
"is" is to check if the address of two variable is the same
== is to check if the value of two variable is the same
None is realized by using a special variable in memory that is the only one, all of the None point to the same address
so 'is' is used to judge if a value is None
but don't use "is" on basic type, the case is much complex:
open python in command line:
>>> a = 10
>>> b = 10
>>> a is b
True
because like Java, a and b all point to 10 in small integer pool
Verify:
>>> a = 1000
>>> b = 1000
>>> a is b
False
what is more:
write
a = 1000
b = 1000
print(a is b)
in test.py
the output is True
Because of another optimizing in Python called Constant Folding
when you run a .py, python will look through entire file, and make all of the constant value point to the same one in memory