leetcode--tree

  1. Binary Tree Inorder Traversal
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<Integer>();
        helper(root, list);
        return list;
    }
    
    public void helper(TreeNode root, List<Integer> list) {
        if(root == null) {
            return;
        }
        helper(root.left, list);
        list.add(root.val);
        helper(root.right, list);
    }
}
  1. Binary Tree Preorder Traversal

class Solution {
    // root left right
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<Integer>();
        
        preorderTraversalHelper(root, result);
        
        return result;
    }
    
    private List<Integer> preorderTraversalHelper(TreeNode node, List<Integer> list) {
        if (node == null) {
            return list;
        }
        
        list.add(node.val);
        
        preorderTraversalHelper(node.left, list);
        preorderTraversalHelper(node.right, list);
        
        return list;
    }
}
  1. Kth Smallest Element in a BST
class Solution {
    int value = Integer.MAX_VALUE;
    int idx = 0;
    public int kthSmallest(TreeNode root, int k) {
        if (root == null)   return -1;
        findKthSmallest(root, k);
        if (idx == k)
            return value;
        
        return -1;
    }
    
    int findKthSmallest(TreeNode root, int k) {
        if (root.left != null) {
            int left = findKthSmallest(root.left, k);
            if (left == k)  return left;
        }
        
        idx++;
        if (idx == k) {
            value = root.val;
            return idx;
        }
        
        if (root.right != null)
            return findKthSmallest(root.right, k);
        else    return idx;
    }
}   
  1. Binary Search Tree Iterator
public class BSTIterator {
    private TreeNode root;
    public BSTIterator(TreeNode root) {
        this.root = root;
    }

    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        return root != null;
    }

    /** @return the next smallest number */
    public int next() {
        if (root == null) {
            return -1;
        }
        
        int ans = 0;
        while (root != null) {
            if (root.left == null) {
                ans = root.val;
                root = root.right;
                break;
            } else {
                TreeNode tmp = root.left;
                while (tmp.right != null && tmp.right != root) {
                    tmp = tmp.right;
                }
                
                if (tmp.right == null) {
                    tmp.right = root;
                    root = root.left;
                } else {
                    ans = root.val;
                    tmp.right = null;
                    root = root.right;
                    break;
                }
            }
        }
        
        return ans;
    }
}  
  1. Binary Tree Level Order Traversal
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
       /** List<List<Integer>> res = new ArrayList<>();
        if(root == null)
            return res;
        Queue<TreeNode> q = new LinkedList<>();
        q.offer(root);
        q.offer(null);
        while(!q.isEmpty() && q.peek()!= null){
            List<Integer> temp = new ArrayList<>();
            TreeNode p = q.poll();
            while(p != null){
                temp.add(p.val);
                if(p.left != null)
                    q.offer(p.left);
                if(p.right != null)
                    q.offer(p.right);
                p = q.poll();
            }
            res.add(temp);
            q.offer(null);
        }
        return res;*/
        List<List<Integer>> res = new ArrayList<>();
        if(root == null)
            return res;
        helper(res,root,0);
        return res;
    }
    
    private void helper(List<List<Integer>> res, TreeNode root, int level){
        if(root == null)
            return;
        if(level >= res.size())res.add(new ArrayList<Integer>());
        res.get(level).add(root.val);
        helper(res,root.left,level+1);
        helper(res,root.right,level+1);
    }
}
  1. Binary Tree Right Side View
class Solution {
    public List<Integer> rightSideView(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        getRightView(root, 0, result);
        return result;
    }
    
    public void getRightView(TreeNode root, int currentDepth, List<Integer> result){
        if(root==null)
            return;
        if(currentDepth == result.size()){
            result.add(root.val);
        }
        getRightView(root.right, currentDepth + 1, result);
        getRightView(root.left, currentDepth + 1, result);
    }
}  
  1. Unique Binary Search Trees
class Solution {
    public int numTrees(int n) {
        if(n <= 0) return 0;
        
        int[] res = new int[n + 1];
        res[0] = 1;
        res[1] = 1;
        for(int i = 2; i <= n; i++){
            for(int j = 0; j < i; j++){
                res[i] += res[j] * res[i - j - 1];
            }
        }
        
        return res[n];
    }
}   
  1. Populating Next Right Pointers in Each Node
public class Solution {
    public void connect(TreeLinkNode root) {
        if (root == null) return ;
        
        if (root.left != null) {
            root.left.next = root.right;
        }
        if (root.right != null) {
            if (root.next != null) {
                root.right.next = root.next.left;
            }
            else { // root.next == null
                root.right.next = null;
            }
        }
        connect(root.left);
        connect(root.right);
    }
}
  1. Binary Tree Zigzag Level Order Traversal
class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        helper(res,root,1);
        return res;
    }
    public void helper(List<List<Integer>> res, TreeNode node,int lvl){
        if(node==null) return;
        if(lvl>res.size()){
            List<Integer> newlist = new ArrayList<>();
            newlist.add(node.val);
            res.add(newlist);
        }
        else{
            if(lvl%2==0) res.get(lvl-1).add(0,node.val);
            else res.get(lvl-1).add(node.val);
        }
        helper(res,node.left,lvl+1);
        helper(res,node.right,lvl+1);
    }
}
  1. Flatten Binary Tree to Linked List
class Solution {
    private TreeNode last = null;
    public void flatten(TreeNode root) {
        if (root == null) {
            return;
        }
        if (last != null) {
            last.left = null;
            last.right = root;
        }
        last = root;
        
        TreeNode right = root.right;
        flatten(root.left);
        flatten(right);
    }
}
public class Solution {
    public void flatten(TreeNode root) {
        if(root == null) return;
        if(root.left != null){
            flatten(root.left);
            TreeNode cur = root;
            TreeNode temp = root.right;
            root.right = root.left;
            root.left = null;
            while(cur.right != null) cur = cur.right;
            cur.right = temp;
            flatten(temp);
        }
        else{
            flatten(root.right);
        }
    }
}
  1. Path Sum II
class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if(root == null) return res;
        List<Integer> temp = new ArrayList<>();        
        helper(root, sum, temp, res);
        return res;
        
    }
    
    private void helper(TreeNode root, int sum, List<Integer> temp, List<List<Integer>> res) {
        if(root == null) return;
        else if (root.val == sum && root.left == null && root.right == null) {
            temp.add(root.val);
            res.add(new ArrayList<>(temp));
            temp.remove(temp.size() - 1);
            return;
        }else 
            temp.add(root.val);
        helper(root.left, sum - root.val, temp, res);
        helper(root.right, sum - root.val, temp, res);  
        temp.remove(temp.size() - 1);
    }
}
  1. Construct Binary Tree from Preorder and Inorder Traversal
class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildTree(preorder,0,inorder,inorder.length-1,0);
        
    }
    private TreeNode buildTree(int[] preorder,int p,int[] inorder,int start,int end){
        if(start<end || p>preorder.length-1)
            return null;
        int val = preorder[p];
        int index = start;
        for(int i=start;i>=end;i--){
            if(val==inorder[i]){
                index = i;
                break;
            }
        }
        TreeNode node = new TreeNode(val);
        node.left = buildTree(preorder,p+1,inorder,index-1,end);
        node.right = buildTree(preorder,p+(index-end)+1,inorder,start,index+1);
        return node;
    }
}
  1. Populating Next Right Pointers in Each Node II
public class Solution {
    public void connect(TreeLinkNode root) {
        while (root != null) {
            TreeLinkNode current = root;
            TreeLinkNode dummy = new TreeLinkNode(0);
            TreeLinkNode p = dummy;
            
            while (current != null) {
                if (current.left != null) {
                    p.next = current.left;
                    p = p.next;
                }
                if (current.right != null) {
                    p.next = current.right;
                    p = p.next;
                }
                current = current.next;
            }
            
            root = dummy.next;
        }
    }
}
  1. Construct Binary Tree from Inorder and Postorder Traversal
class Solution {
    int p_inorder;
    int p_postorder;
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        p_inorder = inorder.length - 1;
        p_postorder = postorder.length-1;
        return helper(inorder, postorder, null);
    }
    public TreeNode helper(int[] inorder, int[] postorder, TreeNode end){
        if(p_postorder < 0){
            return null;
        }
        TreeNode root = new TreeNode(postorder[p_postorder--]);
        if(inorder[p_inorder] != root.val){
            root.right = helper(inorder,postorder,root);
        }
        p_inorder--;
        if((end == null) || (inorder[p_inorder] != end.val)){
            root.left = helper(inorder,postorder,end);
        }
        return root;
    }
}
  1. Lowest Common Ancestor of a Binary Tree
class Solution {
    
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return null;
        }
        if (root == p || root == q) {
            return root;
        }
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if (left == null) {
            return right;
        }
        if (right == null) {
            return left;
        }
        return root;
    } 
    
    // BFS, map<curr, parent>, common ancestor must be p or q or one of their parent
    public TreeNode lowestCommonAncestor1(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || p == null || q == null) {
            return null;
        }
        Map<TreeNode, TreeNode> map = new HashMap<>();
        Deque<TreeNode> queue = new ArrayDeque<TreeNode>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode tmp = queue.poll();
            if (tmp.left != null) {
                map.put(tmp.left, tmp);
                queue.offer(tmp.left);
            }
            if (tmp.right != null) {
                map.put(tmp.right, tmp);
                queue.offer(tmp.right);
            }
        }
        Set<TreeNode> set = new HashSet<>();
        while (p != null) {
            set.add(p);
            p = map.get(p);
        }
        while (!set.contains(q)) {
            q = map.get(q);
        }
        return q;
    }
}  
  1. Count Complete Tree Nodes
public class Solution {
    public int countNodes(TreeNode root) {
        
        if(root==null){
            return 0;
        }
        
        Queue<TreeNode> q = new LinkedList<TreeNode>();
        q.add(root);
        int count=1;
        while(!q.isEmpty()){
            TreeNode temp = q.poll();
            if(temp.val!=-100){
                temp.val=-100;
                
                if(temp.left!=null){
                    q.offer(temp.left);
                    count++;
                }
                
                if(temp.right!=null){
                    q.offer(temp.right);
                    count++;
                }
            }
        }
        return count;
    }
}
  1. Validate Binary Search Tree
class Solution {
    public boolean isValidBST(TreeNode root) {
        return helper(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }
    
    public boolean helper(TreeNode root, long min, long max){
        if(root == null)
            return true;
        
        if(root.val >= max || root.val <= min)
            return false;
        
        return helper(root.left, min, root.val) && helper(root.right, root.val, max);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 202,529评论 5 475
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,015评论 2 379
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 149,409评论 0 335
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,385评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,387评论 5 364
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,466评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,880评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,528评论 0 256
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,727评论 1 295
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,528评论 2 319
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,602评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,302评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,873评论 3 306
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,890评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,132评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,777评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,310评论 2 342

推荐阅读更多精彩内容