Lintcode 二叉树练习

66 二叉树的前序遍历
public class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List res = new ArrayList();
        if (root == null) return res;

        res.add(root.val);
        res.addAll(preorderTraversal(root.left));
        res.addAll(preorderTraversal(root.right));

        return res;
    }
}
  • 非递归
public class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        Stack <TreeNode> stack = new Stack<>();
        List <Integer> res = new ArrayList<>();
        
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                res.add(cur.val);
                stack.push(cur);
                cur = cur.left;
            }

            cur = stack.pop();
            cur = cur.right;
        }

        return res;
    }
}
67 二叉树的中序遍历
public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List res = new ArrayList();
        if (root == null) return res;

        res.addAll(0, inorderTraversal(root.left));
        res.add(root.val);
        res.addAll(inorderTraversal(root.right));

        return res;
    }
}
  • 非递归
public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        Stack <TreeNode> stack = new Stack<>();
        List <Integer> res = new ArrayList<>();
        
        TreeNode cur = root;
        while (cur != null || !stack.isEmpty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }

            cur = stack.pop();
            res.add(cur.val);
            cur = cur.right;
        }

        return res;
    }
}
68 二叉树的后序遍历
public class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List res = new ArrayList();
        if (root == null) return res;

        res.addAll(postorderTraversal(root.left));
        res.addAll(postorderTraversal(root.right));
        res.add(root.val);

        return res;
    }
}
69 二叉树的层次遍历
public class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List res = new ArrayList();
        if (root == null) return res;

		//Queue使用LinkedList
        Queue <TreeNode> q = new LinkedList <TreeNode> ();
        q.offer(root);

        while (!q.isEmpty()) {
            ArrayList <Integer> lst = new ArrayList <Integer> ();
            int n = q.size();
            for (int i = 0; i < n; i ++) {
                TreeNode head = q.poll();       //移除并返回队列头部元素
                if (head.left != null) q.offer(head.left);
                if (head.right != null) q.offer(head.right);

                lst.add(head.val);
            }
            res.add(lst);
        }
        return res;  
    }
}
480 二叉树的所有路径
public class Solution {
    public List<String> binaryTreePaths(TreeNode root) {
        List <String> paths = new ArrayList <> ();

        if (root == null) {
            return paths;
        }

        if (root.left == null && root.right == null) {
            paths.add("" + root.val);
            return paths;
        }

        for (String path : binaryTreePaths(root.left)) {
            paths.add(root.val + "->" + path);
        }
        for (String path : binaryTreePaths(root.right)) {
            paths.add(root.val + "->" + path);
        }

        return paths;
    }
}
93 平衡二叉树
public class Solution {
    int getHeight(TreeNode root) {
        if (root == null) return 0;
        return Math.max(getHeight(root.left), getHeight(root.right)) + 1;
    }

    public boolean isBalanced(TreeNode root) {
        if (root == null) return true;
            
        int lh = getHeight(root.left);
        int rh = getHeight(root.right);

        if (!isBalanced(root.left) || !isBalanced(root.right) || Math.abs(lh - rh) > 1) return false;
        else return true;
    }
}
86 二叉查找树迭代器
#include <bits/stdc++.h>
using namespace std;

int n, a[109];
bool vst[109];
stack <int> s;

int main() {
	cin >> n;
	for (int i = 1; i <= n; i ++) cin >> a[i];
	
	s.push(1);
	vst[1] = true;
	while (s.size()) {
		int u = s.top();
		int l = u * 2;
		int r = u * 2 + 1;
		
		if (a[l] && !vst[l]) {
			s.push(l);
			vst[l] = true;
		}
		else {
			s.pop();
			cout << a[u] << ' ';
			
			if (a[r] && !vst[r]) {
				s.push(r);
				vst[r] = true;
			}
		}
	}

	return 0;
}

/*
7
10 5 15 1 6 12 20

7
10 1 11 0 6 0 12
*/
596 最小子树
public class Solution {
    public int sum(TreeNode root) {
        if (root == null) return 0;
        return root.val + sum(root.left) + sum(root.right);
    }

    public TreeNode findSubtree(TreeNode root) {
        if (root == null) return null;
    
        TreeNode l = findSubtree(root.left);
        TreeNode r = findSubtree(root.right);

        TreeNode ans = root;
        if (l != null && sum(l) < sum(ans)) ans = l;
        if (r != null && sum(r) < sum(ans)) ans = r;

        return ans;
    }
}
597 具有最大平均数的子树
public class Solution {
    public int count(TreeNode root) {
        if (root == null) return 0;
        return 1 + count(root.left) + count(root.right);
    }

    public double sum(TreeNode root) {
        if (root == null) return 0;
        return root.val + sum(root.left) + sum(root.right);
    }

    public TreeNode findSubtree2(TreeNode root) {
        if (root == null) return null;

        TreeNode l = findSubtree2(root.left);
        TreeNode r = findSubtree2(root.right);

        TreeNode ans = root;
        if (l != null && sum(l) / count(l) > sum(ans) / count(ans)) ans = l;
        if (r != null && sum(r) / count(r) > sum(ans) / count(ans)) ans = r;

        return ans;
    }
}
88 最近公共祖先
public class Solution {
	//如果树上有A和B的话,返回LCA(A,B)
	//如果树上只有一个结点的话,返回该结点
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode A, TreeNode B) {
        if (root == null) return null;
        if (root == A || root == B) return root;

        TreeNode l = lowestCommonAncestor(root.left, A, B);     
        TreeNode r = lowestCommonAncestor(root.right, A, B);

        if (l != null && r != null) return root;    //A和B一左一右
        if (l != null) return l;                    //A和B都在左边(默认了在树上一定能找到A和B)
        if (r != null) return r;                    //A和B都在右边(默认了在树上一定能找到A和B)
        return null;                                //两边都没有
    }
}
474 最近公共祖先 II
public class Solution {
    public ParentTreeNode lowestCommonAncestorII(ParentTreeNode root, ParentTreeNode A, ParentTreeNode B) {
        Set <ParentTreeNode> s = new HashSet<>();

        while (A != null) {
            s.add(A);
            A = A.parent;
        }

        while (!s.contains(B)) {
            B = B.parent;
        }
        return B;
    }
}
578 最近公共祖先 III
public class Solution {
    public int count(TreeNode root, TreeNode A, TreeNode B) {
        if (root == null) return 0;

        int res = 0;
        if (root == A || root == B) res = 1;
        return res + count(root.left, A, B) + count(root.right, A, B);
    }
	
	//返回LCA(A,B)
    public TreeNode lowestCommonAncestor3(TreeNode root, TreeNode A, TreeNode B) {
        if (root == null) return null;
        if (A == B) return A;

        TreeNode l = lowestCommonAncestor3(root.left, A, B);
        TreeNode r = lowestCommonAncestor3(root.right, A, B);

        if (l != null) return l;    //LCA在左子树
        if (r != null) return r;    //LCA在右子树

        if (count(root, A, B) == 2) return root;
        return null;
    }
}
453 将二叉树拆成链表
public class Solution {
    public void flatten(TreeNode root) {
        flattenAndReturnLastNode(root);
    }

    private TreeNode flattenAndReturnLastNode(TreeNode root) {
        if (root == null) return null;

        TreeNode leftLast = flattenAndReturnLastNode(root.left);
        TreeNode rightLast = flattenAndReturnLastNode(root.right);
        
        if (leftLast != null) {             //如果左子树为空,则已经符合题意
            leftLast.right = root.right;
            root.right = root.left;
            root.left = null;
        }

        if (rightLast != null) return rightLast;
        if (leftLast != null) return leftLast;
        return root;
    }
}
175 翻转二叉树
public class Solution {
    public void invertBinaryTree(TreeNode root) {
        invertAndReturnFirstNode(root);
    }

    private TreeNode invertAndReturnFirstNode(TreeNode root) {
        if (root == null) return null;

        TreeNode leftFirst = invertAndReturnFirstNode(root.left);
        TreeNode rightFirst = invertAndReturnFirstNode(root.right);
        
        root.left = rightFirst;
        root.right = leftFirst;
        
        return root;
    }
}
1359 有序数组转换为二叉搜索树
public class Solution {
    public TreeNode convertSortedArraytoBinarySearchTree(int[] nums) {
        if (nums == null) return null;
        return buildBST(nums, 0, nums.length - 1);
    }

    private TreeNode buildBST(int[] nums, int l, int r) {
        if (l > r) return null;
        if (l == r) return new TreeNode(nums[l]);

        int mid = l + (r - l) / 2;
        TreeNode node = new TreeNode(nums[mid]);
        node.left = buildBST(nums, l, mid - 1);
        node.right = buildBST(nums, mid + 1, r);
        return node;
    }
}
85 在二叉查找树中插入节点
public class Solution {
    public TreeNode insertNode(TreeNode root, TreeNode node) {
        if (root == null) {
            root = node;
        }
        else if (node.val > root.val) {
            root.right = insertNode(root.right, node);
        }
        else {
            root.left = insertNode(root.left, node);
        }
        return root;
    }
}
1524 在二叉搜索树中查找
public class Solution {
    public TreeNode searchBST(TreeNode root, int val) {
        if (root == null) return null;

        if (val == root.val) return root;
        else if (val > root.val) return searchBST(root.right, val);
        else return searchBST(root.left, val);
    }
}
701 修剪二叉搜索树
public class Solution {
    public TreeNode trimBST(TreeNode root, int minimum, int maximum) {
        if (root == null) return null;

        if (minimum > root.val) {
            return trimBST(root.right, minimum, maximum);
        }
        if (maximum < root.val) {
            return trimBST(root.left, minimum, maximum);
        }
        
        root.left = trimBST(root.left, minimum, maximum);
        root.right = trimBST(root.right, minimum, maximum);
        return root;
    }
}
95 验证二叉查找树
public class Solution {
    public boolean isValidBST(TreeNode root) {
        return judge(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }

    private boolean judge(TreeNode root, long minn, long maxx) {
        if (root == null) return true;

        if (minn >= root.val) return false;
        if (maxx <= root.val) return false;
        if (!judge(root.left, minn, root.val)) return false;
        if (!judge(root.right, root.val, maxx)) return false;

        return true;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值