145. 二叉树的后序遍历
题目来源:145. 二叉树的后序遍历
/** * 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 postorderTraversal = function(root) { if (root === null) return []; let cur = root; let res = []; var addPath=(node) =>{ let arr = []; while(node != null){ arr.push(node.val); node = node.right; } return arr.reverse(); } while (cur) { let node = cur.left; if (node !== null) { while (node !== null && node.right !== null && node.right !== cur) { node = node.right; } if (node.right === null) { node.right = cur; cur = cur.left; continue; } else { node.right = null; res.push(...addPath(cur.left)); } } cur = cur.right; } res.push(...addPath(root)); return res; };
给定一个二叉树,返回它的 后序 遍历。
python3
from typing import List # Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def postorderTraversal(self, root: TreeNode) -> List[int]: def postorder(node: TreeNode): if not node: return postorder(node.left) postorder(node.right) res.append(node.val) res = list() postorder(root) return res class Solution: def postorderTraversal(self, root: TreeNode) -> List[int]: res = list() if not root: return res stack = list() node = root pre = None while stack or node: while node: stack.append(node) node = node.left node = stack.pop() if not node.right or node.right is pre: res.append(node.val) pre = node node = None else: stack.append(node) node = node.right return res class Solution: def postorderTraversal(self, root: TreeNode) -> List[int]: def addPath(node: TreeNode): tmp = list() while node: tmp.append(node.val) node = node.right tmp.reverse() res.extend(tmp) res = list() if not root: return res node = root while node: cur = node.left if cur: while cur.right and cur.right is not node: cur = cur.right if not cur.right: cur.right = node node = node.left continue else: cur.right = None addPath(node.left) node = node.right addPath(root) return res
示例:
输入: [1,null,2,3] 1 \ 2 / 3 输出: [3,2,1]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?