leetcode 199 :Binary Tree Right Side View

时间:2022-05-22 16:32:08
 // 我的代码
package Leetcode;
/**
* 199. Binary Tree Right Side View
* address: https://leetcode.com/problems/binary-tree-right-side-view/
* Given a binary tree, imagine yourself standing on the right side of it,
* return the values of the nodes you can see ordered from top to bottom.
*
*/
import java.util.*; public class BinaryTreeRightSideView {
public static void main(String[] args) {
TreeNode[] tree = new TreeNode[9];
for (int i = 1; i < 9; i++){
tree[i] = new TreeNode(i);
}
TreeNode.link(tree, 1, 2, 3);
TreeNode.link(tree, 2, 4, 5);
TreeNode.link(tree, 3, 6, -1);
TreeNode.link(tree, 5, 7, 8);
// 先序遍历
TreeNode.prePrint(tree[1]);
// solution
List<Integer> result = rightSideView(tree[1]);
System.out.println(result); // solution2
List<Integer> result2 = rightSideView2(tree[1]);
System.out.println(result2); }
/**
* 方法一:时间复杂度较高,需要 O(n),n为树中节点的个数
* @param root
* @return
*/
public static List<Integer> rightSideView(TreeNode root) {
List<Integer> result = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
int childNum = 0;
if (root != null){
queue.offer(root);
while(!queue.isEmpty()){
TreeNode node = queue.poll();
if(node.left!= null){
queue.offer(node.left);
childNum++;
}
if (node.right != null)
{
queue.offer(node.right);
childNum++;
}
System.out.println("queue.size() = " + queue.size());
if (childNum - queue.size() == 0){
result.add(node.val);
childNum = 0;
}
}
} return result; }
 /**
* 方法二
* 别人家的解法,巧妙,速度快且好理解
* @param root
* 中右左 深度优先遍历,保存每层的第一个节点。用当前结果表的size作为标识,这样保证每次存的节点都是第一次出现在该层的节点
* @return
*/
public static List<Integer> rightSideView2(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
if (root == null){
return res;
}
dfs (root, res, 0);
return res;
} public static void dfs (TreeNode root, List<Integer> res, int level){
if (root == null){
return;
}
if (res.size() == level){
res.add (root.val);
}
if (root.right != null){
dfs (root.right, res, level + 1);
}
if (root.left != null){
dfs (root.left, res, level + 1);
}
}