Open Tcdian opened 3 years ago
/**
* 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 result = [];
inorder(root);
return result;
function inorder(root) {
if (root === null) {
return;
}
inorder(root.left);
result.push(root.val);
inorder(root.right);
}
};
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function inorderTraversal(root: TreeNode | null): number[] {
const result: number[] = [];
inorder(root);
return result;
function inorder(root: TreeNode | null) {
if (root === null) {
return;
}
inorder(root.left);
result.push(root.val);
inorder(root.right);
}
};
/**
* 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) {
if (root === null) {
return [];
}
const result = [];
const stack = [];
let patrol = root;
while (patrol !== null || stack.length !== 0) {
while (patrol !== null) {
stack.push(patrol);
patrol = patrol.left;
}
patrol = stack.pop();
result.push(patrol.val);
patrol = patrol.right;
}
return result;
};
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function inorderTraversal(root: TreeNode | null): number[] {
if (root === null) {
return [];
}
const result: number[] = [];
const stack: TreeNode[] = [];
let patrol: TreeNode | null = root;
while (patrol !== null || stack.length !== 0) {
while (patrol !== null) {
stack.push(patrol);
patrol = patrol.left;
}
patrol = stack.pop()!;
result.push(patrol.val);
patrol = patrol.right;
}
return result;
};
94. Binary Tree Inorder Traversal
给定一个二叉树,返回它的 中序 遍历。
Example
Follow up