力扣hot100 二叉树的右视图 递归

‍ 题目地址

力扣hot100 二叉树的右视图 递归_第1张图片

  • 时间复杂度: O ( n ) O(n) O(n)

AC code

/**
 * 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 {
	final List<Integer> ans = new ArrayList<>();

	public List<Integer> rightSideView(TreeNode root)
	{
		dfs(root, 0);
		return ans;
	}

	private void dfs(TreeNode root, int d)
	{
		if (root == null)
			return;
		if (d == ans.size())
			ans.add(root.val);
		dfs(root.right, d + 1);
		dfs(root.left, d + 1);
	}
}

你可能感兴趣的:(力扣,hot100,leetcode,算法,职场和发展)