/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { List<Integer> result = new ArrayList<>(); public List<Integer> rightSideView(TreeNode root) { dfs(root,0); return result; } public void dfs(TreeNode node,int depth){ // 如果当前深度比size大,加入到result; if(depth > result.size()){ result.add(node.val); } else{ // 如果当前深度<= size,将当前result深度的值设为当前值; // 这里代码主要和下发的dfs联动,因为是先dfs left,所以再dfs right时会更新数据 // 最后生成右视图 结果 // 反之,生成左视图结果只需先dfs right,再dfs left result.set(depth,node.val); } dfs(root.left,depth+1); dfs(root.right,depth+1); } } bfs /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public List<Integer> rightSideView(TreeNode root) { List<Integer> result = new ArrayList<>(); if (root == null) return result; Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); int size; while (!queue.isEmpty()) { size = queue.size(); for (int i = 0; i < size; i++) { TreeNode temp = queue.poll(); if (temp.left != null) queue.offer(temp.left); if (temp.right != null) queue.offer(temp.right); if (i == size - 1) result.add(temp.val); } } return result; } }
标签:right,TreeNode,val,视图,queue,二叉树,199,size,result From: https://www.cnblogs.com/JavaYuYin/p/18018721