LeetCode-二叉树总结(二)

层次遍历

使用BFS进行层次遍历。不需要使用两个队列来分别存储当前层的节点和下一层的节点,因为在开始遍历一层的节点时,当前队列中的节点数就是当前层的节点数,只要控制遍历这么多节点数,就能保证这次遍历的都是当前层的节点。

一棵树每层节点的平均数

637. Average of Levels in Binary Tree (Easy)

class Solution {
    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> list = new ArrayList<>();
        if (null == root) {
            return list;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            double aver = 1 / (size * 1.0);
            double sum = 0;
            while (size > 0) {
                TreeNode node = queue.poll();
                sum += node.val;
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
                size--;
            }
            list.add(sum * aver);
        }
        return list;
    }
}

得到左下角的节点

513. Find Bottom Left Tree Value (Easy)

Input:

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

Output:
7
class Solution {
    public int findBottomLeftValue(TreeNode root) {
        int height = maxDepth(root);
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int h = 0, result = -1;
        boolean isEnd = false;
        while (!queue.isEmpty()) {
            h++;
            if (h == height) {
                isEnd = true;
            }
            int size = queue.size();
            while (size > 0) {
                TreeNode node = queue.poll();
                if (isEnd && size == queue.size() + 1) {
                    result = node.val;
                    break;
                }
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
                size--;
            }
            if (isEnd) {
                break;
            }
        }
        return result;
    }
    public int maxDepth(TreeNode root) {
        if (null == root) {
            return 0;
        }
        if (null == root.left && null == root.right) {
            return 1;
        }
        int left = maxDepth(root.left) + 1;
        int right = maxDepth(root.right) + 1;
        return left < right ? right : left;
    }
}

前中后序遍历

    1
   / \
  2   3
 / \   \
4   5   6
  • 层次遍历顺序:[1 2 3 4 5 6]
  • 前序遍历顺序:[1 2 4 5 3 6]
  • 中序遍历顺序:[4 2 5 1 3 6]
  • 后序遍历顺序:[4 5 2 6 3 1]

层次遍历使用 BFS 实现,利用的就是 BFS 一层一层遍历的特性;而前序、中序、后序遍历利用了 DFS 实现。

前序、中序、后序遍只是在对节点访问的顺序有一点不同,其它都相同。

① 前序

void dfs(TreeNode root) {
    visit(root);
    dfs(root.left);
    dfs(root.right);
}

② 中序

void dfs(TreeNode root) {
    dfs(root.left);
    visit(root);
    dfs(root.right);
}

③ 后序

void dfs(TreeNode root) {
    dfs(root.left);
    dfs(root.right);
    visit(root);
}

非递归实现二叉树的前序遍历

144. Binary Tree Preorder Traversal (Medium)

class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (null == root) {
            return list;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.add(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            list.add(node.val);
            if (node.right != null) {
                stack.add(node.right);
            }
            if (node.left != null) {
                stack.add(node.left);
            }
        }
        return list;
    }
}

非递归实现二叉树的后序遍历

145. Binary Tree Postorder Traversal (Hard)

前序遍历为 root -> left -> right,后序遍历为 left -> right -> root。可以修改前序遍历成为 root -> right -> left,那么这个顺序就和后序遍历正好相反。

class Solution {
    public List<Integer> postorderTraversal(TreeNode root) { //left->right->root
        List<Integer> list = new ArrayList<>();
        if (null == root) {
            return list;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.add(root);
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            list.add(node.val);
            if (node.left != null) {
                stack.add(node.left);
            }
            if (node.right != null) {
                stack.add(node.right);
            }
        }
        Collections.reverse(list);
        return list;
    }
}

非递归实现二叉树的中序遍历

94. Binary Tree Inorder Traversal (Medium)

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

Trie

Trie,又称前缀树或字典树,用于判断字符串是否存在或者是否具有某种字符串前缀。

实现一个 Trie

208. Implement Trie (Prefix Tree) (Medium)

class Trie { // Method1

    private class Node {
        Node[] childs = new Node[26];
        boolean isLeaf;
    }

    private Node root = new Node();

    public Trie() {
    }

    public void insert(String word) {
        insert(word, root);
    }

    private void insert(String word, Node node) {
        if (node == null) return;
        if (word.length() == 0) {
            node.isLeaf = true;
            return;
        }
        int index = indexForChar(word.charAt(0));
        if (node.childs[index] == null) {
            node.childs[index] = new Node();
        }
        insert(word.substring(1), node.childs[index]);
    }

    public boolean search(String word) {
        return search(word, root);
    }

    private boolean search(String word, Node node) {
        if (node == null) return false;
        if (word.length() == 0) return node.isLeaf;
        int index = indexForChar(word.charAt(0));
        return search(word.substring(1), node.childs[index]);
    }

    public boolean startsWith(String prefix) {
        return startWith(prefix, root);
    }

    private boolean startWith(String prefix, Node node) {
        if (node == null) return false;
        if (prefix.length() == 0) return true;
        int index = indexForChar(prefix.charAt(0));
        return startWith(prefix.substring(1), node.childs[index]);
    }

    private int indexForChar(char c) {
        return c - 'a';
    }
}
class TrieNode { // Method2
    Map<Character, TrieNode> subNodes = new HashMap<>();
    boolean isEnd = false;
    public TrieNode() {
        
    }
}
class Trie {
    TrieNode root = new TrieNode();
    
    /** Initialize your data structure here. */
    public Trie() {
        
    }
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        if (null == word || 0 == word.length()) {
            return ;
        }
        TrieNode temp = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            TrieNode node = temp.subNodes.get(c);
            if (null == node) {
                node = new TrieNode();
                temp.subNodes.put(c, node);
            }
            temp = node;
            if (i == word.length() - 1) {
                temp.isEnd = true;
            }
        }
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        if (null == word || 0 == word.length()) {
            return false;
        }
        boolean find = false;
        TrieNode temp = root;
        for (int i = 0; i < word.length(); i++) {
            char c = word.charAt(i);
            TrieNode node = temp.subNodes.get(c);
            if (null == node) {
                break;
            }
            temp = node;
            if (i == word.length() - 1 && temp.isEnd) {
                find = true;
            }
        }
        return find;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        if (null == prefix || 0 == prefix.length()) {
            return false;
        }
        boolean find = true;
        TrieNode temp = root;
        for (int i = 0; i < prefix.length(); i++) {
            char c = prefix.charAt(i);
            TrieNode node = temp.subNodes.get(c);
            if (null == node) {
                find = false;
                break;
            }
            temp = node;
        }
        return find;
    }
}

实现一个 Trie,用来求前缀和

677. Map Sum Pairs (Medium)

Input: insert("apple", 3), Output: Null
Input: sum("ap"), Output: 3
Input: insert("app", 2), Output: Null
Input: sum("ap"), Output: 5
class Trie {
    Map<Character, Trie> subNodes = new HashMap<>();
    int value = 0;
    public Trie() {
        this.value = 0;
    }
}
class MapSum {
    Trie root = new Trie();
    Set<String> set = new HashSet<>();
    /** Initialize your data structure here. */
    public MapSum() {
        
    }
    
    public void insert(String key, int val) {
        if (null == key || 0 == key.length()) {
            return ;
        }
        boolean exist = false;
        if (!set.contains(key)) {
            set.add(key);
        } else {
            exist = true;
        }
        Trie temp = root;
        for (int i = 0; i < key.length(); i++) {
            char c = key.charAt(i);
            Trie node = temp.subNodes.get(c);
            if (null == node) {
                node = new Trie();
                temp.subNodes.put(c, node);
            }
            temp = node;
            if (exist) {
                temp.value = val;
            } else {
                temp.value += val;
            }
        }
    }
    
    public int sum(String prefix) {
        if (null == prefix || 0 == prefix.length()) {
            return 0;
        }
        Trie temp = root;
        int result = 0;
        for (int i = 0; i < prefix.length(); i++) {
            char c = prefix.charAt(i);
            Trie node = temp.subNodes.get(c);
            if (null == node) {
                break;
            }
            temp = node;
            if (i == prefix.length() - 1) {
                result = temp.value;
                break;
            }
        }
        return result;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值