Problem: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.
题目:给定一个二叉树,输出从右侧看到的节点(大致就是每层的最右侧的节点).
思路:做的二叉树的深度遍历
1.节点是否为空,不为空则记录节点。
2.递归查找根节点的左孩子,是否为空,不为空记录在该层节点数组中
3.递归查找根节点的右孩子,是否为空,不为空记录在该层节点数组中
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> ret = new ArrayList<Integer>();
if (root == null) {
return ret;
}
int height = getHeight(root, 0);
TreeNode[] edgeMap = new TreeNode[height];
setRightEdge(root, 0, edgeMap);
for (int i = 0; i < height; i++) {
ret.add(edgeMap[i].val);
}
return ret;
}
// refined for this problem
public void setRightEdge(TreeNode node, int l, TreeNode[] rightEdge) {
if (node == null) {
return;
}
rightEdge[l]=node;
setRightEdge(node.left, l+1,rightEdge);
setRightEdge(node.right, l+1,rightEdge);
}
// get the height of treenode
public int getHeight(TreeNode node, int l) {
if (node == null) {
return l;
}
return Math.max(getHeight(node.left, l + 1), getHeight(node.right, l + 1));
}
}