Leetcode_257_Binary Tree Paths

97 篇文章 0 订阅
94 篇文章 18 订阅

本文是在学习中的总结,欢迎转载但请注明出处:http://blog.csdn.net/pistolove/article/details/49432057



Given a binary tree, return all root-to-leaf paths.

For example, given the following binary tree:

   1
 /   \
2     3
 \
  5

All root-to-leaf paths are:

["1->2->5", "1->3"]


思路:

(1)题意为给定一棵树,找出所有从根到叶子节点的路径。

(2)该题实为树的深度优先遍历。本题是使用递归的方法来进行求解的,从根节点开始,若左子树不为空,则遍历左子树,若左子树的左孩子不为空,则遍历左孩子,否则遍历右孩子.....直到遍历完最后一个叶子节点为止。使用非递归算法,则需要设定一个栈来保存左右子树,也很好实现,这里不累赘了。

(3)详情见下方代码。希望本文对你有所帮助。


package leetcode;

import java.util.ArrayList;
import java.util.List;
import leetcode.utils.TreeNode;

public class Binary_Tree_Paths {

	public static void main(String[] args) {
		TreeNode r = new TreeNode(1);
		TreeNode r1 = new TreeNode(2);
		TreeNode r2 = new TreeNode(3);
		TreeNode r3 = new TreeNode(5);

		r.left = r1;
		r.right = r2;
		r1.right = r3;

		binaryTreePaths(r);
	}

	public static List<String> binaryTreePaths(TreeNode root) {
		List<String> result = new ArrayList<String>();

		if (root != null) {
			getpath(root, String.valueOf(root.val), result);
		}
		return result;
	}

	private static void getpath(TreeNode root, String valueOf,
			List<String> result) {
		if (root.left == null && root.right == null)
			result.add(valueOf);

		if (root.left != null) {
			getpath(root.left, valueOf + "->" + root.left.val, result);
		}

		if (root.right != null) {
			getpath(root.right, valueOf + "->" + root.right.val, result);
		}
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值