leetCode: 112. Path Sum
Problem
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
解題思路:
采用遞歸的思想,(root->sum) 意味著 (root.left->sum - root.value || root.right->sum - root.value)
如果當前節(jié)點為null則返回false,如果當前節(jié)點為葉子節(jié)點則判斷該節(jié)點值是不是等于sum剿干,否則遞歸扔字。
代碼如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null) return false;
if(root.left==null&&root.right==null&&root.val==sum){
return true;
}
return(hasPathSum(root.right,sum-root.val)||hasPathSum(root.left,sum-root.val));
}
}
LeetCode 226 Invert Binary Tree
Problem:
Invert a binary tree.
4
/ \
2 7
/ \ / \
1 3 6 9
to
4
/ \
7 2
/ \ / \
9 6 3 1
Trivia:This problem was inspired by this original tweet by Max Howell:Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.
解題思路:
還是用遞歸的思想矩距。
代碼如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode invertTree(TreeNode root) {
if(root==null){
return null;
}
if(root.left==null&&root.right==null){
return root;
}
root.left = invertTree(root.left);
root.right = invertTree(root.right);
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
return root;
}
}