力扣----8. 二叉树的中序遍历(JavaScript, Java实现)

题目描述:

给定一个二叉树,返回它的中序 遍历。

示例:

输入: [1,null,2,3]
1
  \
    2
  /
3

输出: [1,3,2]

 

JavaScript实现

递归

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var inorderTraversal = function(root) {
    if(!root) return [];
    return [...inorderTraversal(root.left), root.val, ...inorderTraversal(root.right)]
};

 

非递归

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[]}
 */

var inorderTraversal = function(root) {
    const [noVisit, visited] = [0, 1];
    let res = [];
    const stack = [[noVisit, root]];
    while(stack.length){
        let [isVisited, root] = stack.pop();
        if(!root) continue
        if(!isVisited) {
            stack.push([noVisit, root.right])
            stack.push([visited, root])
            stack.push([noVisit, root.left])
        }else{
            res.push(root.val)
        }
    }
    return res;
};

 

 

Java实现:

待补充

posted @ 2020-06-10 11:09  灭世的蜜糖  阅读(165)  评论(0编辑  收藏  举报