Tree

538. Convert BST to Greater Tree

Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.

Example:

Input: The root of a Binary Search Tree like this:
5
/
2 13

Output: The root of a Greater Tree like this:
18
/
20 13

题意就是每个节点的值是本身加上所有比它大的节点的值,所有最右边是所有节点的和20。BST一定要想到inorder遍历。这道题反过来in order遍历。

class Solution {
    int sum = 0;
    public TreeNode convertBST(TreeNode root) {
        // inverse inorder traversal
        // right root left
        if (root == null) {
            return null;
        }
        convertBST(root.right);
        root.val = root.val + sum;
        sum = root.val;
        convertBST(root.left);
        
        return root;
    }
}

315. Count of Smaller Numbers After Self

You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i].

Example:

Given nums = [5, 2, 6, 1]

To the right of 5 there are 2 smaller elements (2 and 1).
To the right of 2 there is only 1 smaller element (1).
To the right of 6 there is 1 smaller element (1).
To the right of 1 there is 0 smaller element.
Return the array [2, 1, 1, 0].

有两个点。一是找5以后比5小的数,要想到可以从后往前找。二是想到构建一个二叉树来解题,node里再存一个count记录左子树的个数。有几个细节没想清楚,一是如果出现相等的数字怎么办。二是把结果的list当参数传进去。最后学习如何手写一个BST。

class Solution {
    /**
    1. add into tree reversely
    2. how to handle equally
    */
    public List<Integer> countSmaller(int[] nums) {
        List<Integer> res = new ArrayList<>();
        // construct a binary search tree
        BST bst = new BST(); 
        // add from right to left
        for (int i = nums.length - 1; i >= 0; i--) {
            bst.insert(nums[i], res);
        }
        Collections.reverse(res);

        return res;
    }
    
    class TreeNode {
    TreeNode left, right;
    int count; // number of nodes in the left substree
    int val; // root's value
    public TreeNode(int val) {
        this.count = 0;
        this.left = this.right = null;
        this.val = val;
        }
    }
    
    class BST {
        TreeNode root;
        public BST () {
            root = null;
        }

        public void insert (int num, List<Integer> res) {
            root = insert(root, num, 0, res);
        }
        
        private TreeNode insert(TreeNode node, int val, int sum, List<Integer> res) {
            if (node == null) {
                node = new TreeNode(val);
                res.add(sum);
                return node;
            }
            if (node.val > val) {
                node.count++;
                node.left = insert(node.left, val, sum, res);
            } else {
                node.right = insert(node.right, val, sum + node.count + (node.val == val ? 0 : 1), res);
            }
            return node;
        }
    }
}

199. Binary Tree Right Side View

Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.

For example:
Given the following binary tree,
1 <---
/
2 3 <---
\
5 4 <---
You should return [1, 3, 4].

用level order做。需要注意的是一开始没有考虑到这种情况。
1
/
2 3
\
5

655. Print Binary Tree

Input:
1
/
2 3

4
Output:
[["", "", "", "1", "", "", ""],
["", "2", "", "", "", "3", ""],
["", "", "4", "", "", "", ""]]

数组的长度是树的宽度,个数是树的高度,用分治做,递归函数有哪些参数需要注意。剩下就是细节,Math函数返回double,list如何在指定位置插入。最好把结果的二维list初始化好 这样更方便。

class Solution {
    public List<List<String>> printTree(TreeNode root) {
        // get the height and width of the given tree
        int height = getHeight(root);
        int width = (int) Math.pow(2, height) - 1; // pow return double 
        List<List<String>> res = new ArrayList<>();
        for (int i = 0; i < height; i++) {
            List<String> list = new ArrayList<>();
            for (int j = 0; j < width; j++) {
                list.add("");
            }
            res.add(list);
        }
        // fill the list of each level 
        helper(root, res, 0, 0, width - 1);
        return res;
    }
    // helper function, fill list
    public void helper(TreeNode root, List<List<String>> res, int level, int left, int right) {
        if (root == null) {
            return;
        }
        int mid = (left + right) / 2;
        res.get(level).set(mid, String.valueOf(root.val));
        helper(root.left, res, level + 1, left, mid - 1);
        helper(root.right, res, level + 1, mid + 1, right);
        
    }
    
    public int getHeight(TreeNode root) {
        if (root == null) return 0;
        return 1 + Math.max(getHeight(root.left), getHeight(root.right));
    }
}

遍历

  • 前序
    public List<Integer> preorderTraversal(TreeNode root) {
        Stack<TreeNode> stack = new Stack<TreeNode>();
        List<Integer> preorder = new ArrayList<Integer>();
        
        if (root == null) {
            return preorder;
        }
        
        stack.push(root);
        while (!stack.empty()) {
            TreeNode node = stack.pop();
            preorder.add(node.val);
            if (node.right != null) {
                stack.push(node.right);
            }
            if (node.left != null) {
                stack.push(node.left);
            }
        }
        
        return preorder;
    }
  • Level Order
  • In Order

543. Diameter of Binary Tree

Given a binary tree
1
/
2 3
/ \
4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

用MaxDepth做

173. Binary Search Tree Iterator

Implement an iterator of a BST, next() and hasNext()

BST的inorder traversal是有序的,关键是弹出leftmost之后如何能找到父亲节点,想到用stack
关键是知道BST的inorder和使用stack保存父亲节点

98. Validate Binary Search Tree

如题

一种是分治,分到左右子树。把当前value传到左子树做最大值,传到右子树做最小值,如果当前值小于最大值,大于最小值,而且左右子树都true,那么返回true。感觉跟正常的分治有点区别。
BST要想到inorder遍历,用stack记录每个左节点,到了leftmost之后开始pop,存在右节点就处理右节点,没有就再pop获取其父亲。然后pop出来,再处理右节点

public List<Integer> inorderTraversal(TreeNode root) {
    List<Integer> list = new ArrayList<>();
    if(root == null) return list;
    Stack<TreeNode> stack = new Stack<>();
    while(root != null || !stack.empty()){
        while(root != null){
            stack.push(root);
            root = root.left;
        }
        root = stack.pop();
        list.add(root.val);
        root = root.right;
        
    }
    return list;
}

314. Binary Tree Vertical Order Traversal

  • 观察得知用level order遍历
  • 每个node还需要有一个offset信息 (root是0,左孩子是-1,右孩子是1)想到用另一个queue和level order的queue同步更新
  • Keep track of leftmost and rightmost,最后从hashmap拿数据时候用
    public List<List<Integer>> verticalOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        // column - points
        Map<Integer, List<Integer>> map = new HashMap<>();
        // traverse the tree
        Queue<TreeNode> q = new LinkedList<>();
        Queue<Integer> c = new LinkedList<>();
        q.offer(root);
        c.offer(0);
        // keep track of leftmost and rightmost
        int left = 0, right = 0;
        
        while(!q.isEmpty()) {
            int column = c.poll();
            TreeNode cur = q.poll();
            if (map.containsKey(column)) {
                map.get(column).add(cur.val);
            } else {
                List<Integer> list = new ArrayList<>();
                list.add(cur.val);
                map.put(column, list);
            }
            if (cur.left != null) {
                q.offer(cur.left);
                c.offer(column - 1);
                left = Math.min(left, column - 1);
            }
            if (cur.right != null) {
                q.offer(cur.right);
                c.offer(column + 1);
                right = Math.max(right, column + 1);
            }
        }
        for (int i = left; i <= right; i++) {
            res.add(map.get(i));
        }
        return res;
        
    }

652. Find Duplicate Subtrees

Given a binary tree, return all duplicate subtrees. For each kind of duplicate subtrees, you only need to return the root node of any one of them.

Two trees are duplicate if they have the same structure with same node values.

递归的序列化每个子树

class Solution {
    // serialize the tree
    public List<TreeNode> findDuplicateSubtrees(TreeNode root) {
        Map<String, Integer> map = new HashMap<>(); // store every serialized subtree, if duplicate store it into res
        List<TreeNode> list = new ArrayList<>();
        serialize(root, map, list);
        return list;
    }
    public String serialize(TreeNode node, Map<String, Integer> map, List<TreeNode> list) {
        if (node == null) {
            return "#";
        }
        String key = node.val + "," + serialize(node.left, map, list) + "," + serialize(node.right, map, list);
        map.put(key, map.getOrDefault(key, 0) + 1);
        if (map.get(key) == 2) {
            list.add(node);
        }
        return key;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,826评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,968评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,234评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,562评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,611评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,482评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,271评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,166评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,608评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,814评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,926评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,644评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,249评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,866评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,991评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,063评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,871评论 2 354

推荐阅读更多精彩内容

  • 总结类型: 完全子树(#222) BST(左右子树值的性质,注意不仅要满足parent-child relatio...
    __小赤佬__阅读 693评论 0 0
  • 94. Binary Tree Inorder Traversal 中序 inorder:左节点->根节点->右节...
    Morphiaaa阅读 537评论 0 0
  • 做个简单练习,题目关于点菜。要求用户注册登录之后,来到点菜页面,点菜页面数据从后台数据库获取后页面渲染出来。用户选...
    2010jing阅读 720评论 4 4
  • 什么是xshell? xshell是一个终端模拟软件,简单来说我们可以通过xshell连接上服务器上的linux操...
    ppmoon阅读 2,941评论 0 50
  • 第一次邂逅,你还是个少年 我和你是同座,你笑的样子真的吸引了我 于是…… 午餐时帮你打扫 作业帮你记好 考试时一起...
    夙醉银阅读 160评论 0 0