根左右
function preorderTraversal(root: TreeNode | null): number[] {
let res = []
function dfs(root: TreeNode | null) {
if (root) {
res.push(root.val)
dfs(root.left)
dfs(root.right)
}
}
dfs(root)
return res
};
左根右
function inorderTraversal(root: TreeNode | null): number[] {
let res = []
function dfs(root: TreeNode | null) {
if (root) {
dfs(root.left)
res.push(root.val)
dfs(root.right)
}
}
dfs(root)
return res
};
左右根
function postorderTraversal(root: TreeNode | null): number[] {
let res = []
function dfs(root: TreeNode | null) {
if (root) {
dfs(root.left)
dfs(root.right)
res.push(root.val)
}
}
dfs(root)
return res
};
比较左子树的深度+1和右子树深度+1 取最大
function maxDepth(root: TreeNode | null): number {
if (!root) return 0
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1
};