|
1 | 1 | package com.fishercoder.solutions;
|
2 | 2 |
|
3 |
| -/** |
4 |
| - * Created by fishercoder on 4/23/17. |
5 |
| - */ |
6 |
| - |
7 | 3 | import com.fishercoder.common.classes.TreeNode;
|
8 | 4 |
|
9 |
| -/**Binary Tree Tilt |
| 5 | +/** |
| 6 | + * 563. Binary Tree Tilt |
10 | 7 | *
|
11 | 8 | * Given a binary tree, return the tilt of the whole tree.
|
12 |
| -
|
13 |
| - The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. |
14 |
| - Null node has tilt 0. |
15 |
| - The tilt of the whole tree is defined as the sum of all nodes' tilt. |
| 9 | + * The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values |
| 10 | + * and the sum of all right subtree node values. |
| 11 | + * Null node has tilt 0. |
| 12 | + * The tilt of the whole tree is defined as the sum of all nodes' tilt. |
16 | 13 |
|
17 | 14 | Example:
|
18 | 15 | Input:
|
|
32 | 29 | The sum of node values in any subtree won't exceed the range of 32-bit integer.
|
33 | 30 | All the tilt values won't exceed the range of 32-bit integer.*/
|
34 | 31 | public class _563 {
|
| 32 | + public static class Solution1 { |
35 | 33 |
|
36 |
| - int tilt = 0; |
| 34 | + int tilt = 0; |
37 | 35 |
|
38 |
| - public int findTilt(TreeNode root) { |
39 |
| - findTiltDfs(root); |
40 |
| - return tilt; |
41 |
| - } |
42 |
| - |
43 |
| - public int findTiltDfs(TreeNode root) { |
44 |
| - if (root == null) { |
45 |
| - return 0; |
46 |
| - } |
47 |
| - int leftTilt = 0; |
48 |
| - if (root.left != null) { |
49 |
| - leftTilt = findTiltDfs(root.left); |
| 36 | + public int findTilt(TreeNode root) { |
| 37 | + findTiltDfs(root); |
| 38 | + return tilt; |
50 | 39 | }
|
51 |
| - int rightTilt = 0; |
52 |
| - if (root.right != null) { |
53 |
| - rightTilt = findTiltDfs(root.right); |
54 |
| - } |
55 |
| - if (root.left == null && root.right == null) { |
56 |
| - return root.val; |
| 40 | + |
| 41 | + public int findTiltDfs(TreeNode root) { |
| 42 | + if (root == null) { |
| 43 | + return 0; |
| 44 | + } |
| 45 | + int leftTilt = 0; |
| 46 | + if (root.left != null) { |
| 47 | + leftTilt = findTiltDfs(root.left); |
| 48 | + } |
| 49 | + int rightTilt = 0; |
| 50 | + if (root.right != null) { |
| 51 | + rightTilt = findTiltDfs(root.right); |
| 52 | + } |
| 53 | + if (root.left == null && root.right == null) { |
| 54 | + return root.val; |
| 55 | + } |
| 56 | + tilt += Math.abs(leftTilt - rightTilt); |
| 57 | + return leftTilt + rightTilt + root.val; |
57 | 58 | }
|
58 |
| - tilt += Math.abs(leftTilt - rightTilt); |
59 |
| - return leftTilt + rightTilt + root.val; |
60 | 59 | }
|
61 | 60 |
|
62 | 61 | }
|
0 commit comments