257.Binary Tree Paths
Tags: [tree], [binary_tree], [path], [recursion], [backtracking]
Com: {fb}
Link: https://leetcode.com/problems/binary-tree-paths/\#/description
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"]
Solution: Backtracking
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
if not root:
return []
result = []
buff = []
self.binary_tree_paths_helper(root, buff, result)
return result
def binary_tree_paths_helper(self, root, buff, result):
# base case
if not root:
return
if not root.left and not root.right:
buff.append(root.val)
result.append('->'.join([str(x) for x in buff]))
buff.pop()
return
buff.append(root.val)
self.binary_tree_paths_helper(root.left, buff, result)
self.binary_tree_paths_helper(root.right, buff, result)
buff.pop()
Revelation:
- The real base case is 'if not root.left and not root.right' at where it is a leaf node.
- We do backtracking, we first try to buff.append(), after the recursion call, we must do buff.pop().
Note:
- Time complexity = O(n), n is the number of nodes in the given tree. Because each node we only visited once.