前序遍历
python
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
res = []
def preorder(root):
if root == None:
return
res.append(root.val)
preorder(root.left)
preorder(root.right)
preorder(root)
return res
java
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
preorder(root, res);
return res;
}
void preorder(TreeNode root, List<Integer> res){
if (root == null){
return;
}
res.add(root.val);
preorder(root.left, res);
preorder(root.right, res);
}
}
后序遍历
java
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
postorder(root, res);
return res;
}
void postorder(TreeNode root, List<Integer> res){
if (root == null){
return;
}
postorder(root.left, res);
postorder(root.right, res);
res.add(root.val);
}
}
python
class Solution(object):
def postorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
res = []
def postorder(root):
if root == None:
return
postorder(root.left)
postorder(root.right)
res.append(root.val)
postorder(root)
return res
中序遍历
java
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
inorder(root, res);
return res;
}
void inorder(TreeNode root, List<Integer> res){
if (root == null){
return;
}
inorder(root.left, res);
res.add(root.val);
inorder(root.right, res);
}
}
python
class Solution(object):
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
# 保存结果
res = []
def inorder(root):
if root == None:
return
inorder(root.left)
res.append(root.val)
inorder(root.right)
inorder(root)
return res