二叉树的中序遍历

2020-04-02
二叉树的中序遍历

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

题解:
思路1: 递归
递归的方法最简单 容易理解
 
/**
 * 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) {
  let arr = [];
  let fn = function (node) {
    if (node !== null) {
      fn(node.left);
      arr.push(node.val);
      fn(node.right);
    }
  }
  fn(root);
  return arr;
};
思路2: 栈
用栈的思想遍历树 每到一个节点 A,因为根的访问在中间,将 A 入栈。然后遍历左子树,接着访问 A,最后遍历右子树。
在访问完 A 后,A 就可以出栈了。因为 A 和其左子树都已经访问完成。
 
var inorderTraversal = function (root) {
  let stack = []; // 遍历树时用的栈
  let res = []; // 结果
  while (stack.length > 0 || root !== null) { // 当栈不为空或是当前节点不为null时进入循环
    if (root !== null) { // 若当前节点有值
      stack.push(root.val); // 将当前节点推入栈中
      root = root.left; // 继续遍历root.left
    } else {
      const tmp = stack.pop(); // 如果栈不为空且当前节点为null 说明到了最底部
      res.push(tmp); // 将栈的最后一项出栈 这一项就是当前节点的父节点 也就是结果的第一个值
      root = tmp.right; // 再遍历该节点的right
    }
  }
  return res;
};
原文地址:https://www.cnblogs.com/lanpang9661/p/12617566.html