class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } @Override public String toString(){ if(this == null) return ""; StringBuilder sb = new StringBuilder(); LinkedList<TreeNode> queue = new LinkedList<Tr…
Problem Link: https://oj.leetcode.com/problems/binary-tree-level-order-traversal/ Traverse the tree level by level using BFS method. # Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # se…
Problem Link: https://oj.leetcode.com/problems/binary-tree-zigzag-level-order-traversal/ Just BFS from the root and for each level insert a list of values into the result. # Definition for a binary tree node # class TreeNode: # def __init__(self, x):…
Problem Link: https://oj.leetcode.com/problems/binary-tree-level-order-traversal-ii/ Use BFS from the tree root to traverse the tree level by level. The python code is as follows. # Definition for a binary tree node # class TreeNode: # def __init__(s…
Problem Link: http://oj.leetcode.com/problems/binary-tree-maximum-path-sum/ For any path P in a binary tree, there must exists a node N in P such that N is the ancestor node of all other nodes in P. We call such N as the root of P, or P roots at N. T…
Problem Link: http://oj.leetcode.com/problems/binary-tree-preorder-traversal/ Even iterative solution is easy, just use a stack storing the nodes not visited. Each iteration, pop a node and visited it, then push its right child and then left child in…
Problem Link: http://oj.leetcode.com/problems/binary-tree-postorder-traversal/ The post-order-traversal of a binary tree is a classic problem, the recursive way to solve it is really straightforward, the pseudo-code is as follows. RECURSIVE-POST-ORDE…
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). For example:Given binary tree {3,9,20,#,#,15,7}, 3 / \ 9 20 / \ 15 7 return its bottom-up level order tr…
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"] Credits:Special thanks to @jianchao.li.fighter for adding this pro…
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. For example:Given the following binary tree, 1 <--- / \ 2 3 <--- \ \ 5 4 <--- You should return [1, 3,…