leetCode解题报告5道题(三)

题目一:

Binary Tree Zigzag Level Order Traversal

Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3
   / \
  9  20
    /  \
   15   7

return its zigzag level order traversal as:

[
  [3],
  [20,9],
  [15,7]
]

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


分析:层次遍历的变形哈.没啥太大的变化,看代码理解下哈!


/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) {
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        if (root == null)
            return result;
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        int k = 1;
        ArrayList<TreeNode> list = new ArrayList<TreeNode>();
        
        while (!queue.isEmpty()){
            list.clear();
            while (!queue.isEmpty()){
                list.add(queue.remove());
            }
            ArrayList<Integer> arrays = new ArrayList<Integer>();
            
            for(int i=0; i<list.size(); ++i){
                TreeNode node = list.get(i);
                if (k % 2 == 1){
                    arrays.add(list.get(i).val);
                }else{
                    arrays.add(list.get(list.size()-1-i).val);
                }
                if (node.left != null)
                    queue.add(node.left);
                if (node.right != null)
                    queue.add(node.right);
            }
            k++;
            result.add(arrays);
        }
        return result;
    }
}


题目二:

Convert Sorted Array to Binary Search Tree

 Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

题意:给你一个array数组,让你求出这个数组所能组成的一个平衡的二叉树,很明显的递归问题哈,用分治的思想把中间的结点作为根结点,再一直递归下去就可以了哈!!

AC代码:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode sortedArrayToBST(int[] num) {
        if (num.length == 0){
            return null;
        }
        return buildBST(num, 0, num.length-1);
    }
    /*
        递归调用
    */
    public TreeNode buildBST(int[] num, int left, int right){
        /*当left > right 的时候,表示是叶子结点的孩子了,返回null*/
        if (left > right){
            return null;
        }
        /*取中间值,作为根结点的值*/
        int middle = (right + left) / 2;
        TreeNode root = new TreeNode(num[middle]);
        /*求出左右孩子*/
        root.left = buildBST(num, left, middle-1);
        root.right = buildBST(num, middle+1, right);
        return root;
    }
}

类似的题目:

Convert Sorted List to Binary Search Tree

 Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

题意:跟上面的一样,只不过数组换成了链表!!果断要知道如何快速求出链表中间的那个结点哈~

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; next = null; }
 * }
 */
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    
    public TreeNode sortedListToBST(ListNode head) {
        if (head == null){
            return null;
        }
        return buildBST(head, null);
    }
    
    public TreeNode buildBST(ListNode left, ListNode right){
        if (right == null && left == null){
            return null;
        }
        if (right != null && right.next == left){
            return null;
        }
        /*求链表中间结点的前一个结点 Begin*/
        ListNode preLeft = new ListNode(0);
        preLeft.next = left;
        ListNode tempNode = left;
        ListNode preMiddleNode = preLeft;
        /*求链表中间结点的具体方法*/
        while (tempNode != right && tempNode.next != right){
            preMiddleNode = preMiddleNode.next;
            tempNode = tempNode.next.next;
        }
        /*求链表中间结点的前一个结点 End*/
        
        /*递归咯!*/
        ListNode middleNode = preMiddleNode.next;
        TreeNode root = new TreeNode(middleNode.val);
        root.left = buildBST(left, preMiddleNode);
        root.right = buildBST(preMiddleNode.next.next, right);
        return root;
    }
}

题目三:

Surrounded Regions(考察深度搜索)

 

Given a 2D board containing 'X' and 'O', capture all regions surrounded by 'X'.

A region is captured by flipping all 'O's into 'X's in that surrounded region.

For example,

X X X X
X O O X
X X O X
X O X X

After running your function, the board should be:

X X X X
X X X X
X X X X
X O X X


分析:给你一个数组,里面包含了x(或者X) 还有 o(或者O),要求我们把o(或者O)被x(或X)包围的情况,转换成  o -> x  而  O -> X

这个题目,其实是典型的广度搜索吧。。

解题方法:居然所有的边界o(或者O),我们都认为它是不被包围的,那么我们只要从边界入手就可以了...我们用一个二维数组flags来确定每个位置该出现什么字母,如:flags[row][col] = 0 则 row行 col列出现的字母为x(或者X), flags[row][col] = 1 则 row行 col列出现的字母为o(或者O), 

把所有处于边界的o(或者O)加入到queue中,然后就是一个典型的BFS了,只需要循环出队入队,并做好标记,如果从队列中出去的话,证明这个位置一定是没有被X所包围的,那么标记这个位置flags[row][col] = 1;

之后只需要循环flags这个二维数组就可以了。


AC代码:

public class Solution {
    private int[][] flags;//用来标记每个位置的字母
	private int rowLength;//行数
	private int colLength;//列数
	
	/*自定义放入queue中的数据结构类型*/
	class Node{
		int i;
		int j;
		public Node(int i, int j) {
			this.i = i;
			this.j = j;
		}
	}
	
	public void solve(char[][] board){
	    /*初始化*/
		rowLength = board.length;
		if (rowLength == 0 || board[0].length == 0)
			return ;
		colLength = board[0].length;
		
		/*初始化flags, queue, 然后把board[][]中的边界字母为o(或者O)的取出放入queue*/
		flags = new int[rowLength][colLength];
		Queue<Node> queue = new LinkedList<Node>();
		for (int i=0; i<rowLength; ++i){
			for (int j=0; j<colLength; ++j){
				if (i == 0 || i == rowLength - 1){
					if (board[i][j] == 'o' || board[i][j] == 'O'){
						queue.add(new Node(i,j));
					}
				}else{
					if (j == 0 || j == colLength - 1){
						if (board[i][j] == 'o' || board[i][j] == 'O'){
							queue.add(new Node(i,j));
						}
					}
				}
				
			}
		}
		/*BFS*/
		while (!queue.isEmpty()){
			Node node = queue.remove();
			int row = node.i;
			int col = node.j;
			flags[row][col] = 1;
			//left
			if (col-1 >= 0 && (board[row][col-1] == 'o' || board[row][col-1] == 'O' )&& flags[row][col-1] == 0){
				queue.add(new Node(row,col-1));
			}
			//right
			if (col+1 < colLength && (board[row][col+1] == 'o' || board[row][col+1] == 'O') && flags[row][col+1] == 0){
				queue.add(new Node(row,col+1));
			}
			//up
			if (row-1 >= 0 && (board[row-1][col] == 'o' || board[row-1][col] == 'O')&& flags[row-1][col] == 0){
				queue.add(new Node(row-1,col));
			}
			//down
			if (row+1 < rowLength && (board[row+1][col] == 'o' || board[row+1][col] == 'O')&& flags[row+1][col] == 0){
				queue.add(new Node(row+1,col));
			}
		}
		/*重新赋值board[][]*/
		for (int i=0; i<rowLength; ++i){
			for (int j=0; j<colLength; ++j){
				if (flags[i][j] == 0){
					if (board[i][j] == 'o'){
						board[i][j] = 'x';
					}else if (board[i][j] == 'O'){
						board[i][j] = 'X';
					}
				}
				//System.out.print(board[i][j] + " ");
			}
			//System.out.println("");
		}
	}
}


题目四:

Balanced Binary Tree

Given a binary tree, determine if it is height-balanced.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

分析:考察的其实就是对平衡二叉树概念的理解,和二叉树求深度的方法的掌握

一棵二叉树如果满足平衡的条件,那么包括它自身,和它的任何一个子树的左右子树的深度之差必须要小于2,这样问题就转换成了递归的了,一直递归下去,如果不满足条件,则把全局的标志flag置为false;


/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    private boolean flag = true;

	public boolean isBalanced(TreeNode root) {
		calDeepthByTree(root);
		return flag;
	}

	public int calDeepthByTree(TreeNode root) {
		if (root == null)
			return 0;
		if (root.left == null && root.right == null)
			return 1;

		int deepLeft = 0;
		int deepRight = 0;
		deepLeft = calDeepthByTree(root.left) + 1;
		deepRight = calDeepthByTree(root.right) + 1;
		if (Math.abs(deepRight - deepLeft) >= 2) {
			flag = false;
		}
		return deepRight > deepLeft ? deepRight : deepLeft;
	}
}


题目五:


Minimum Depth of Binary Tree

 

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.


分析: 给我们一个二叉树,要求出从根结点到叶子结点的最短的路径(依旧还是递归哈!)

很简单,直接看代码:


AC代码:

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int minDepth(TreeNode root) {
        /*递归结束条件*/
        if (root == null)
            return 0;
        if (root.left == null && root.right == null)
            return 1;
        
        int leftdepth = minDepth(root.left);
        int rightdepth = minDepth(root.right);
        
        /*当其中左右子树有一支是为null的时候,那么路径也只有另外一支了,不管多长都只能选那条路了*/
        if (leftdepth == 0){
            return rightdepth+1;
        }
        if (rightdepth == 0){
            return leftdepth+1;
        }
        
        /*返回左右子树中较小的一边*/
        return leftdepth > rightdepth ? rightdepth + 1 : leftdepth + 1;
    }
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值