題目大意:給定一顆二叉樹,求該二叉樹的右視圖,即從右往左看,求能看到的二叉樹的結點,比如[1,2,3]看到的是1,3。
思路:
1)這道題挺有意思,首先得明確,題目的隱含意思就是要求二叉樹的每一層的最後一個結點(從左到右)。
2)既然二叉樹分層次,就需要利用層次遍歷遍歷二叉樹。
3)層次遍歷二叉樹的時候,最重要的內容是知道當前遍歷的層哪個是最後一個結點。
4) 設置變量記錄當前層在遍歷隊列中剩下的結點書——thisLevelRemaind,和下一層一共有多少個結點數——nextLevelHas,這樣的話每當對頭出隊,thisLevelRemaind--,每當有新節點入隊,nextLevelHas++。
5)最後,如果thisLevelRemaind爲1時,則把該結點加入結果集合中。
Java代碼:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<TreeNode> listQueue = new ArrayList<TreeNode>();
List<Integer> resultList = new ArrayList<Integer>();
if (root == null)
return resultList;
int thisLevelRemaind = 1;
int nextLevelHas = 0;
listQueue.add(root);
while (!listQueue.isEmpty()) {
TreeNode headNode = listQueue.get(0);
if (headNode.left != null) {
listQueue.add(listQueue.get(0).left);
nextLevelHas++;
}
if (headNode.right != null) {
listQueue.add(headNode.right);
nextLevelHas++;
}
if (thisLevelRemaind == 1) {
resultList.add(headNode.val);
}
listQueue.remove(0);
thisLevelRemaind--;
if (thisLevelRemaind == 0) {
thisLevelRemaind = nextLevelHas;
nextLevelHas = 0;
}
}
return resultList;
}
}