LeetCode刷题(2)

来源:互联网 发布:7.0神器数据库 编辑:程序博客网 时间:2024/06/05 02:30

4、 Add Digits

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

For example:

Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.

Follow up:
Could you do it without any loop/recursion in O(1) runtime?

一个数中的所有数字之和能被9整除,则该数能被9整除。

public class Solution {    public int addDigits(int num) {        if(num<=9)            return num;        else if(num%9==0)            return 9;        else            return num%9;    }}
public class Solution {    public int addDigits(int num) {        return 1 + (num-1)%9;    }}

5、 Maximum Depth of Binary Tree

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    public int maxDepth(TreeNode root) {        if(root==null)            return 0;        else             return 1+Math.max(maxDepth(root.left),maxDepth(root.right));    }}

6、 Invert Binary Tree

Invert a binary tree.

4
/ \
2 7
/ \ / \
1 3 6 9

to

4
/ \
7 2
/ \ / \
9 6 3 1

/** * 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;        TreeNode temp = root.left;        root.left = invertTree(root.right);        root.right = invertTree(temp);        return root;    }}
public TreeNode invertTree(TreeNode root) {    if (root != null) {        TreeNode temp = root.left;        root.left = root.right;        root.right = temp;        invertTree(root.left);        invertTree(root.right);    }    return root;}
8 0