通过递归实现二叉树的遍历
二叉树的前序
var preorderTraversal = function(root) {
if (!root) return []
const res = []
order(root, res)
return res;
};
var order = function(node,res){
if(!node){
return node;
}
res.push(node.val);
order(node.left,res);
order(node.right,res);
return res;
}
中序
var inorderTraversal = function(root) {
if(!root){
return [];
}
let res = [];
order(root,res)
return res;
};
var order = function(node,res){
if(!node){
return node;
}
order(node.left,res);
res.push(node.val);
order(node.right,res);
return res;
}
后序遍历
var postorderTraversal = function(root) {
if(!root){
return [];
}
let res = [];
order(root,res);
return res;
};
var order = function(node,res){
if(!node){
return node;
}
order(node.left,res);
order(node.right,res);
res.push(node.val);
return res;
}
参考
1. leetcode postorder 2. leetcode preorder 3. leetcode inorder 4.代码随想录
|