Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

LeetCode题解:590. N叉树的后序遍历,栈,JavaScript,详细注释 #192

Open
chencl1986 opened this issue Oct 16, 2020 · 0 comments

Comments

@chencl1986
Copy link
Owner

原题链接:https://leetcode-cn.com/problems/n-ary-tree-postorder-traversal/

解题思路:

  1. 后序遍历输出节点的顺序是从下到上,从左到右。
  2. 我们可以使用栈来进行遍历,每次循环入栈元素都为从上到下,从左到右。
  3. 那么每次循环时出栈元素的顺序都为从上到下,从右到左。
  4. 但此时的栈的元素输出顺序与需要的结果顺序正好相反。
  5. 解决方案就是将输出的结果插入到结果数组的头部,这样最终输出结果顺序就为从下到上,从左到右。
/**
 * @param {Node} root
 * @return {number[]}
 */
var postorder = function (root) {
  let result = []; // 保存结果
  let stack = []; // 使用栈遍历
  root && stack.push(root); // 二叉树存在时才开始遍历

  // 遍历二叉树,直到清空栈,即为遍历了所有节点
  while (stack.length) {
    // 从栈中弹出元素,顺序为从上到下,从右到左
    const node = stack.pop();

    // 将节点的值插入到结果数组的前端
    // 保证了输出结果的顺序为从下到上,从左到右
    result.unshift(node.val);

    // 将子节点按照从左到右入栈,保证了出栈顺序
    if (node.children) {
      for (const child of node.children) {
        stack.push(child);
      }
    }
  }

  return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant