Skip to content

Latest commit

 

History

History
69 lines (62 loc) · 1.58 KB

145.二叉树的后序遍历.md

File metadata and controls

69 lines (62 loc) · 1.58 KB

145.二叉树的后序遍历

/*
 * @lc app=leetcode.cn id=145 lang=typescript
 *
 * [145] 二叉树的后序遍历
 */

// @lc code=start
/**
 * 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 postorderTraversal(root: TreeNode | null): number[] {}
// @lc code=end

解法 1: Morris

function postorderTraversal(root: TreeNode | null): number[] {
  let res: number[] = []
  while (root) {
    if (root.right) {
      let pre = root.right
      while (pre.left && pre.left !== root) {
        pre = pre.left!
      }
      if (!pre.left) {
        pre.left = root
        res.push(root.val)
        root = root.right
      } else {
        root = root.left
      }
    } else {
      res.push(root.val)
      root = root.left
    }
  }
  return res.reverse()
}

Case

test.each([
  { input: { root: [1, null, 2, 3] }, output: [3, 2, 1] },
  { input: { root: [] }, output: [] },
  { input: { root: [1] }, output: [1] },
  { input: { root: [1, null, 2] }, output: [2, 1] },
  { input: { root: [1, 2] }, output: [2, 1] },
  { input: { root: [3, 1, 2] }, output: [1, 2, 3] },
])('input: root = $input.root', ({ input: { root }, output }) => {
  expect(postorderTraversal(BinaryTree.deserialize(root))).toEqual(output)
})