aboutsummaryrefslogtreecommitdiff
path: root/max_diff_node_ancestor.rs
blob: 671bd2750262b4e4803715968c29f96d058605bc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
use std::cmp;
use std::rc::Rc;
use std::cell::RefCell;

#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
    pub val: i32,
    pub left: Option<Rc<RefCell<TreeNode>>>,
    pub right: Option<Rc<RefCell<TreeNode>>>
}

struct MinMax {
    min: i32,
    max: i32,
    ans: i32
}

impl TreeNode {
    #[inline]
    pub fn new(val: i32) -> Self {
        TreeNode {
            val,
            left: None,
            right: None
        }
    }
}

impl Solution {
    fn minMax(node_ref: Rc<RefCell<TreeNode>>) -> MinMax {
        let node = node_ref.borrow();
        let mut a = MinMax {
            min: node.val,
            max: node.val,
            ans: 0
        };
        if node.left.is_none() && node.right.is_none() {
            a
        }  else {
            let children = vec![&node.left, &node.right];
            for child_option in children.iter() {
                if let Some(child) = child_option {
                    let c = Self::minMax(Rc::clone(&child));
                    a.ans = cmp::max(a.ans, c.ans);
                    a.ans = cmp::max(a.ans, (node.val - c.min).abs());
                    a.ans = cmp::max(a.ans, (node.val - c.max).abs());
                    a.min = cmp::min(a.min, c.min);
                    a.max = cmp::max(a.max, c.max);
                }
            }
            a
        }
    }
    pub fn max_ancestor_diff(root: Option<Rc<RefCell<TreeNode>>>) -> i32 {
        if let Some(node_ref) = root {
            Self::minMax(Rc::clone(&node_ref)).ans
        } else {
            panic!("bad input");
        }
    }
}