513.找树左下角的值
题目链接:513. 找树左下角的值 - 力扣(LeetCode)
非递归:
class Solution {
public int findBottomLeftValue(TreeNode root) {
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
TreeNode ans = null;
while (!q.isEmpty()) {
ans = q.poll();
TreeNode b = ans;
q.offer(null);
while(b != null) {
if(b.left != null) {
q.offer(b.left);
}
if(b.right != null) {
q.offer(b.right);
}
b = q.poll();
}
}
return ans.val;
}
}
递归:
class Solution {
public int findBottomLeftValue(TreeNode root) {
int h = height(root);
return helper(root, h).val;
}
private TreeNode helper(TreeNode root,int h){
if(h == 1) {
return root;
}
TreeNode left = null, right = null;
if(root.left != null) {
left = helper(root.left, h-1);
}
if(root.right != null) {
right = helper(root.right, h-1);
}
return (left == null) ? right : left;
}
private int height(TreeNode root) {
return root == null ? 0 : 1 + Math.max(height(root.left), height(root.right));
}
}
106.从中序与后序遍历序列构造二叉树
题目链接:106. 从中序与后序遍历序列构造二叉树 - 力扣(LeetCode)
递归:
class Solution {
int[] post;
HashMap<Integer,Integer> map = new HashMap<>();
public TreeNode buildTree(int[] inorder, int[] postorder) {
bulidHash(map, inorder);
post = postorder;
return buildTree(0, inorder.length -1, 0, postorder.length -1);
}
private void bulidHash(HashMap<Integer,Integer> a,int[] inorder) {
for(int i = 0; i < inorder.length; ++i) {
a.put(inorder[i], i);
}
}
private TreeNode buildTree(int i1,int i2,int p1,int p2) {
if(i1 > i2 || p1 > p2) {
return null;
}
int root = post[p2];
int ri = map.get(root);
TreeNode node = new TreeNode(root);
node.left = buildTree(i1, ri-1, p1, p1 + ri - i1 -1);
node.right = buildTree(ri + 1, i2, p1 + ri - i1, p2 - 1);
return node;
}
}
非递归:
105.从前序与中序遍历序列构造二叉树
题目链接:105. 从前序与中序遍历序列构造二叉树 - 力扣(LeetCode)
递归:
class Solution {
int[] post;
HashMap<Integer,Integer> map = new HashMap<>();
public TreeNode buildTree(int[] inorder, int[] postorder) {
bulidHash(map, inorder);
post = postorder;
return buildTree(0, inorder.length -1, 0, postorder.length -1);
}
private void bulidHash(HashMap<Integer,Integer> a,int[] inorder) {
for(int i = 0; i < inorder.length; ++i) {
a.put(inorder[i], i);
}
}
private TreeNode buildTree(int i1,int i2,int p1,int p2) {
if(i1 > i2 || p1 > p2) {
return null;
}
int root = post[p2];
int ri = map.get(root);
TreeNode node = new TreeNode(root);
node.left = buildTree(i1, ri-1, p1, p1 + ri - i1 -1);
node.right = buildTree(ri + 1, i2, p1 + ri - i1, p2 - 1);
return node;
}
}
非递归:
112.路径总和
递归:
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if(root == null) {
return false;
}
if(root.val == targetSum) {
if(leaf(root)) {
return true;
}
}
return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
}
private boolean leaf(TreeNode root) {
return root.left == null && root.right == null;
}
}
非递归:
113.路径总和II
题目链接:113. 路径总和 II - 力扣(LeetCode)
代码