LeetCode-590N叉树的后序遍历

https://leetcode-cn.com/problems/n-ary-tree-postorder-traversal/

给定一个 N 叉树,返回其节点值的后序遍历。

例如,给定一个 3叉树 :

在这里插入图片描述

返回其后序遍历: [5,6,3,2,4,1].

public class LeetCode_590_555 {
	public static void main(String[] args) {

		LeetCode_590_555 leetcode = new LeetCode_590_555();

		Node node2 = new Node(2, new ArrayList<Node>());
		Node node4 = new Node(4, new ArrayList<Node>());
		Node node5 = new Node(5, new ArrayList<Node>());
		Node node6 = new Node(6, new ArrayList<Node>());

		List<Node> chList3 = new ArrayList<Node>();
		chList3.add(node5);
		chList3.add(node6);
		Node node3 = new Node(3, chList3);

		List<Node> chList1 = new ArrayList<Node>();
		chList1.add(node3);
		chList1.add(node2);
		chList1.add(node4);
		Node root = new Node(1, chList1);

		List<Integer> res = leetcode.postorder(root);
		for (int i = 0; i < res.size(); i++) {
			System.out.println(res.get(i));
		}
	}

	List<Integer> res = new ArrayList<Integer>();

	public List<Integer> postorder(Node root) {
		helper(root);
		return res;
	}

	public void helper(Node root) {
		if (root == null) {
			return;
		}
		int s = root.children.size();
		for (int i = 0; i < s; i++) {
			helper(root.children.get(i));
		}
		res.add(root.val);
	}

	public static class Node {
		public int val;
		public List<Node> children;

		public Node() {
		}

		public Node(int _val, List<Node> _children) {
			val = _val;
			children = _children;
		}
	};
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值