章三 二叉树和分制

1 前序遍历三种方式

非递归  1

    public ArrayList<Integer> preorderTraversal(TreeNode root) {
        // write your code here
        ArrayList<Integer> res = new ArrayList<Integer>();
        if (root == null) {
            return res;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
       while (!stack.empty()) {
            TreeNode node = stack.pop();
            res.add(node.val);
            if (node.right != null) {
                stack.push(node.right);
            }
            if (node.left != null) {
                stack.push(node.left);
            }
        }
        return res;
    }
View Code

1 错  栈中应该先加入右节点

非递归2

    public ArrayList<Integer> preorderTraversal(TreeNode root) {
        // write your code here
        ArrayList<Integer> res = new ArrayList<Integer>();
        if (root == null) {
            return res;
        }
        Stack<TreeNode> stack = new Stack<>();
        while (root != null || !stack.isEmpty()){
            while (root != null) {
                res.add(root.val);
                stack.push(root);
                root = root.left;
            }
            TreeNode node = stack.pop();
            root = node.right;
        }
        return res;
    }
View Code

递归1

    public ArrayList<Integer> preorderTraversal(TreeNode root) {
        // write your code here
        ArrayList<Integer> res = new ArrayList<Integer>();
        if (root == null) {
            return res;
        }
        help(root, res);
        return res;
    }
    void help(TreeNode root, List<Integer> res) {
        if (root == null) return;
        res.add(root.val);
        help(root.left, res);
        help(root.right, res);
    }
View Code

递归2

    public ArrayList<Integer> preorderTraversal(TreeNode root) {
        // write your code here
        ArrayList<Integer> res = new ArrayList<Integer>();
        if (root == null) {
            return res;
        }
        List<Integer> left = preorderTraversal(root.left);
        List<Integer> right = preorderTraversal(root.right);
        res.add(root.val);
        res.addAll(left);
        res.addAll(right);
        return res;
    }
View Code

2 中序遍历非递归

 非递归

    public ArrayList<Integer> inorderTraversal(TreeNode root) {
        // write your code here
        ArrayList<Integer> res = new ArrayList<Integer>();
        if (root == null) {
            return res;
        }
        LinkedList<TreeNode> stack = new LinkedList<TreeNode>();
        while (root != null || !stack.isEmpty()){
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            TreeNode node = stack.pop();
            res.add(node.val);
            root = node.right;
        }
        return res;
    }
View Code

3 后序遍历

非递归

    public ArrayList<Integer> postorderTraversal(TreeNode root) {
        // write your code here
        ArrayList<Integer> res = new ArrayList<Integer>();
        if (root == null) {
            return res;
        }
        TreeNode pre = null;
        LinkedList<TreeNode> stack = new LinkedList<TreeNode>();
        while (root != null || !stack.isEmpty()) {
            if (root != null) {
                stack.push(root);
                root = root.left;
            } else {
                TreeNode node = stack.peek();
                if (node.right == null || pre == node.right) {
                    stack.pop();
                    res.add(node.val);
                    pre = node;
                } else {
                    root = node.right;
                }
            }
        }
        return res;
    }
View Code

时间太长,不熟练。

4 归并排序  先局部有序,在整体有序

    public void sortIntegers2(int[] a) {
        mergesort(a, 0, a.length - 1);
    }
    void mergesort(int[] a, int start, int end) {
        if (start < end) {
            int mid = start + (end - start) / 2;
            mergesort(a, start, mid);
            mergesort(a, mid + 1, end);
            merge(a, start, mid, end);
        }
    }
    void merge(int[] a, int start, int mid, int end) {
        int[] m = new int[end - start + 1];
        int i = start;
        int j = mid + 1;
        int k = 0;
        while (i <= mid && j <= end) {
            if (a[i] <= a[j]) {
                m[k++] = a[i++];
            } else {
                m[k++] = a[j++];
            }
        }
        while (i <= mid) {
            m[k++] = a[i++];
        }
        while (j <= end) {
            m[k++] = a[j++];
        }
        for (int h = 0; h < k; h++) {
            a[start + h] = m[h];
        }
    }
View Code

时间长,不熟练

5快速排序

    public void sortIntegers2(int[] a) {
        quicksort(a, 0, a.length - 1);
    }
    void quicksort(int[] a, int start, int end) {
        if (start < end) {
            int mid = start + (end - start) / 2;
            int p = partion(a, start, end);
            quicksort(a, start, p - 1);
            quicksort(a, p + 1, end);
        }
    }
    int partion(int[] a, int start, int end) {
        int x = a[end];
        int i = start - 1;
        for (int j = start; j < end; j++) {
            if (a[j] <= x) {
                i++;
                swap(a, i, j);
            }
        }
        swap(a, i + 1, end);
        return i + 1;
    }
    void swap(int[] a, int l, int r) {
        int temp = a[l];
        a[l] = a[r];
        a[r] = temp;
    }
}
View Code

很久没做,忘了

6 二叉树的最大深度

    public int maxDepth(TreeNode root) 
    {
        if (root == null) {
            return 0;
        }
        return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
    }
View Code

7 平衡二叉树

    public boolean isValidBST(TreeNode root) 
    {
        return help(root) != -1;
    }
    int help(TreeNode root) {
        if (root == null) return 0;
        int left = help(root.left);
        int right = help(root.right);
        if (left == -1 || right == -1 || Math.abs(left - right) > 1){
            return -1;
        }
        return Math.max(left, right) + 1;
    }
View Code

8 Binary Tree Maximum Path Sum

public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: An integer.
     */
    public int maxPathSum(TreeNode root) 
    {
        ResultType result = help(root);
        return result.max;
    }
    public ResultType help(TreeNode root) {
        if (root == null) {
            return new ResultType(0, Integer.MIN_VALUE);
        }
        ResultType left = help(root.left);
        ResultType right = help(root.right);
        
        int singlePath = Math.max(left.single, right.single) + root.val;
        singlePath = Math.max(singlePath, 0);
        
        int maxPath = Math.max(left.max, right.max);
        maxPath = Math.max(maxPath, left.single + right.single + root.val);
        return new ResultType(singlePath, maxPath);
    }
}
class ResultType {
    int single;
    int max;
    ResultType(int single, int max) {
        this.single = single;
        this.max = max;
    }
}
View Code

不熟练

9 Lowest Common Ancestor

    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode a, TreeNode b) {
        // write your code here
        if (root == null || a == root || b == root) return root;
        TreeNode left = lowestCommonAncestor(root.left, a, b);
        TreeNode right = lowestCommonAncestor(root.right, a, b);
        if (left != null && right != null) {
            return root;
        }
        return left != null ? left : right;
    }
View Code

不熟练

10 二叉树层次遍历

    public List<List<Integer>> levelOrder(TreeNode root) {
        // write your code here
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        // 1 初始化
        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            ArrayList<Integer> res = new ArrayList<>(size);
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                res.add(node.val);
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            result.add(res);
        }
        return result;
    }
View Code

11 Binary Tree Zigzag Level Order Traversal

        List<List<Integer>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        // 1 初始化
        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            ArrayList<Integer> res = new ArrayList<>(size);
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                res.add(node.val);
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            result.add(res);
        }
        return result;
View Code

12 Validate Binary Search Tree

    public boolean isValidBST(TreeNode root) 
    {
        return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }
    boolean isValidBST(TreeNode root, long min, long max) {
        if (root == null) return true;
        if (root.val <= min || root.val >= max) return false;
        return isValidBST(root.left, min, root.val) &&
               isValidBST(root.right, root.val, max);
    }
View Code

错误   范围

13  Insert Node in a Binary Search Tree

    public TreeNode insertNode(TreeNode root, TreeNode node) {
        if(root == null) return node;
        if (root.val < node.val) {
            root.right = insertNode(root.right, node);
        } else {
            root.left = insertNode(root.left, node);
        }
        return root;
    }
View Code
    public TreeNode insertNode(TreeNode root, TreeNode node) {
        if(root == null) return node;
        TreeNode tep = root;
        TreeNode last = null;
        while (tep != null) {
            last = tep;
            if (tep.val < node.val) {
                tep = tep.right;
            } else {
                tep = tep.left;
            }
        }
        if (last != null) {
            if (last.val < node.val) {
                last.right = node;
            } else {
                last.left = node;
            }
        }
        return root;
    }
View Code

不熟悉

14   Search Range in Binary Search Tree

    public ArrayList<Integer> searchRange(TreeNode root, int k1, int k2) {
        // write your code here
        ArrayList<Integer> res = new ArrayList<>();
        help(root, k1, k2, res);
        return res;
    }
    void help(TreeNode root, int k1, int k2, List<Integer> res) {
        if (root == null) return;
        if (root.val > k1) {
            help(root.left, k1, k2, res);
        }
        if (k1 <= root.val && root.val <= k2) {
            res.add(root.val);
        }
        if (root.val < k2) {
            help(root.right, k1, k2, res);
        }
    }
View Code

 不熟悉

15  Implement iterator of Binary Search Tree

public class BSTIterator {
    //@param root: The root of binary tree.
    Stack<TreeNode> stack = new Stack<>();
    TreeNode next = null;
    
    void addNodeToStack(TreeNode root) {
        while (root != null) {
            stack.push(root);
            root = root.left;
        }
    }
    public BSTIterator(TreeNode root) {
        // write your code here
        next = root;
    }
    

    //@return: True if there has next node, or false
    public boolean hasNext() {
        // write your code here
        if (next != null) {
            addNodeToStack(next);
            next = null;
        }
        return !stack.isEmpty();
    }
    
    //@return: return next node
    public TreeNode next() {
        // write your code here
        if (!hasNext()){
            return null;
        }
        TreeNode cur = stack.pop();
        next = cur.right;
        return cur;
    }
}
View Code

不熟悉

posted on 2017-08-25 15:05  wheleetcode  阅读(160)  评论(0编辑  收藏  举报