写一个树
// 定义二叉树节点
function TreeNode(val, left, right) {
this.val = (val === undefined ? 0 : val)
this.left = (left === undefined ? null : left)
this.right = (right === undefined ? null : right)
}
// 示例使用
const root = new TreeNode(1,
new TreeNode(2,
new TreeNode(4),
new TreeNode(5)),
new TreeNode(3,
null,
new TreeNode(7))
);
二叉树的中序遍历
https://leetcode.cn/problems/binary-tree-inorder-traversal/description/
递归
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number[]}
*/
var inorderTraversal = function(root) {
const res = [];
const inorder = (root) => {
if (!root) {
return;
}
inorder(root.left);
res.push(root.val);
inorder(root.right);
}
inorder(root);
return res;
};
二叉树的先序遍历
var inorderTraversal = function(root) {
const res = [];
const inorder = (root) => {
if (!root) {
return;
}
res.push(root.val);
inorder(root.left);
inorder(root.right);
}
inorder(root);
return res;
};
二叉树的后序遍历
var inorderTraversal =
标签:right,TreeNode,val,inorder,javascript,面试,root,leetcode,left
From: https://blog.csdn.net/weixin_43342290/article/details/141866669