LC.145.Post-order Traversal Of Binary Tree

本文介绍了一种迭代方式实现二叉树的后序遍历算法,并提供了详细的代码示例。通过此方法,可以有效地获取二叉树节点的后序遍历顺序。

https://leetcode.com/problems/binary-tree-postorder-traversal/description/

Description

Implement an iterative, post-order traversal of a given binary tree, return the list of keys of each node in the tree as it is post-order traversed.

Examples

        5

      /    \

    3        8

  /   \        \

1      4        11

Post-order traversal is [1, 4, 3, 11, 8, 5]

Corner Cases

  • What if the given binary tree is null? Return an empty list in this case.

How is the binary tree represented?

We use the level order traversal sequence with a special symbol "#" denoting the null node.

For Example:

The sequence [1, 2, 3, #, #, 4] represents the following binary tree:

    1

  /   \

 2     3

      /

    4

 

 

/**
 * public class TreeNode {
 *   public int key;
 *   public TreeNode left;
 *   public TreeNode right;
 *   public TreeNode(int key) {
 *     this.key = key;
 *   }
 * }
 */

 

 1 public List<Integer> postOrder(TreeNode root) {
 2     // Write your solution here
 3     if(root == null ) return new ArrayList<Integer>() ; 
 4       List<Integer> res = new ArrayList<Integer>() ; 
 5     traverse(root, res) ; 
 6     return res ; 
 7   }
 8   private void traverse(TreeNode root, List<Integer> res){
 9       //base case 
10     if(root == null ) return ; 
11     traverse(root.left, res); 
12     traverse(root.right, res) ; 
13     res.add(root.key); 
14   }

 

 

转载于:https://www.cnblogs.com/davidnyc/p/8476838.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值