print out the path from one node to another in binary tree

Question:

You are given one binary tree, find the path from one node to another.

public static LinkedList<Integer> printPath(Node root, Node n1, Node n2) {
		Node temp = root;
		LinkedList<Integer> rootToN1 = new LinkedList<Integer>();
		LinkedList<Integer> rootToN2 = new LinkedList<Integer>();

		pathFromRootToNode(temp, n1, new ArrayList<Integer>(), rootToN1);
		pathFromRootToNode(root, n2, new ArrayList<Integer>(), rootToN2);
		int prev = 0;;
		while (true) {
			if (rootToN1.size() > 0 && rootToN2.size() > 0 && rootToN1.get(0) == rootToN2.get(0)) {
				prev = rootToN1.get(0);
				rootToN1.remove();
				rootToN2.remove();
			} else {
				rootToN2.add(0, prev);
				for (Integer i : rootToN1) {
					rootToN2.add(0, i);
				}
				break;
			}
		}
		return rootToN2;		
	}
	// the path from root the a specific node
	public static void pathFromRootToNode(Node root, Node n, ArrayList<Integer> stack, LinkedList<Integer> list) {
		if (root == null) return;
		stack.add(root.value);
		if (root == n) {
			list.addAll(stack);
		}
		
		if (root.leftChild != null) {
			pathFromRootToNode(root.leftChild, n, stack, list);
		}
		if (root.rightChild != null) {
			pathFromRootToNode(root.rightChild, n, stack, list);
		}
		// after searching the left part, we need to remove the added value
		stack.remove(stack.size() - 1);
	}

class Node {
    Node leftChild = null;
    Node rightChild = null;
    int value;

    Node(int value) {
        this.value = value;
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值