LeetCode-Algorithms-[Mid]面试题34. 二叉树中和为某一值的路径

面试题34. 二叉树中和为某一值的路径

LeetCode-Algorithms-[Mid]面试题34. 二叉树中和为某一值的路径_第1张图片

第一版代码:不回溯的做法

	private List> res;
	int sum;

	public List> pathSum(TreeNode root, int sum) {
		initial(sum);
		getSumPath(root, 0, new LinkedList());
		return res;
	}

	private void getSumPath(TreeNode t, int crrSum, List list) {
		if (t == null) {
			return;
		}
		int val = t.val;
		crrSum += val;
		if (t.left == null && t.right == null && crrSum == this.sum) {
			list.add(val);
			res.add(list);
		}else {
			list.add(val);
			List lefList = list;
			List rightList = copy(list);
			getSumPath(t.left, crrSum, lefList);
			getSumPath(t.right, crrSum, rightList);
		}
	}

	private void initial(int sum) {
		res = new LinkedList>();
		this.sum = sum;
	}

	private List copy(List list) {
		List res = new LinkedList();
		Iterator it = list.iterator();
		while (it.hasNext()) {
			int temp = (int) it.next();
			res.add(temp);
		}
		return res;
	}

更优的写法:(回溯法,传参换成int)

	private List> res;
	private List list;

	public List> pathSum(TreeNode root, int sum) {
		initial();
		getPathSum(root, sum);
		return res;
	}

	private void getPathSum(TreeNode node, int crrSum) {
		if (node == null) {
			return;
		}
		int val = node.val;
		crrSum -= val;
		list.add(val);
		if (crrSum == 0 && node.left == null && node.right == null) {
			List temp = new LinkedList(list);
			res.add(temp);
		} else {
			getPathSum(node.left, crrSum);
			getPathSum(node.right, crrSum);
		}
		int n = list.size();
		if (n > 0) {
			list.remove(n - 1);
		}
	}

	private void initial() {
		res = new LinkedList>();
		list = new LinkedList();
	}

 

你可能感兴趣的:(LeetCode)