Java实现N叉树数据结构

 

package MaximumDepthNAryTreeNew;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

// class representing node of n-ary tree
class Node {
	int val;
	ArrayList<Node> children;

	public Node(int val) {
		this.val = val;
		this.children = new ArrayList<>();
	}
}

class NumberOfSiblingsOfAGivenNodeInNAryTree {

	public static int maxDepth(Node root) {
		if (root == null)
			return 0;
		int max = 0;
		for (Node n : root.children) {
			max = Math.max(max, maxDepth(n));
		}
		return max + 1;
	}

	private static int siblings(Node root, int target) {
		// if the given node is equals to the root or root is null, return 0
		if (root == null || root.val == target) {
			return 0;
		}
		// create a queue of nodes
		Queue<Node> queue = new LinkedList<>();
		// push the root to queue
		queue.add(root);
		// do a BFS of the tree
		while (!queue.isEmpty()) {
			// remove one element from the queue
			Node curr = queue.poll();
			// traverse its children
			for (int i = 0; i < curr.children.size(); i++) {
				// current child
				Node currChild = curr.children.get(i);
				// if current child is the target, return (parent's children count - 1)
				if (currChild.val == target) {
					return (curr.children.size() - 1);
				}
				// add the child to the queue
				queue.add(currChild);
			}
		}
		// if there is no match, return -1
		return -1;
	}

	public static void main(String[] args) {
		// Example n-ary tree
		Node root = new Node(51);
		// children of 51
		root.children.add(new Node(10));
		root.children.add(new Node(41));
		root.children.add(new Node(6));
		root.children.add(new Node(32));
		// children of 10
		root.children.get(0).children.add(new Node(53));
		// children of 41
		root.children.get(1).children.add(new Node(95));
		// children of 6
		root.children.get(2).children.add(new Node(28));
		// children of 32
		root.children.get(3).children.add(new Node(9));
		root.children.get(3).children.add(new Node(11));
		// children of 53
		root.children.get(0).children.get(0).children.add(new Node(5));
		root.children.get(0).children.get(0).children.add(new Node(7));
		// children of 11
		root.children.get(3).children.get(1).children.add(new Node(3));
		root.children.get(3).children.get(1).children.add(new Node(8));
		System.out.println(siblings(root, 10));
		System.out.println(siblings(root, 11));
		System.out.println(maxDepth(root));
	}
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值