本文主要是介绍Binary Tree Right Side View,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Notes:站在右边看,即层次遍历,只保存每一层的最后一个值!
/*** Definition for binary tree* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/
public class Solution {public List<Integer> rightSideView(TreeNode root) {List<Integer> list = new ArrayList<Integer>();if (root == null){return list;}Queue<TreeNode> queue = new LinkedList<TreeNode>();queue.add(root);TreeNode tmpNode = null;while(!queue.isEmpty()){int size = queue.size();int i = 0;while (i < size) {tmpNode = queue.poll();
// innerList.add(tmpNode.val);if(tmpNode.left != null){queue.add(tmpNode.left);}if (tmpNode.right != null) {queue.add(tmpNode.right);}if(i == (size - 1)){list.add(tmpNode.val);}i++;}
// list.add(innerList); } return list;}
}
这篇关于Binary Tree Right Side View的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!