• 199 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. For example: Given the following binary tree, 1 <--- / 2 3 <--- 5 4 <--- You should return [1, 3, 4]. Credits: Special thanks to @amrsaqr for adding this problem and creating all test cases.

    算法: 根右左, 尾递归

    容器: list 尾递归

    corner case: 右没有怎么办, 加一个输入值表示深度,  list.size() 也表示深度

    The core idea of this algorithm:

    1.Each depth of the tree only select one node.

    2.View depth is current size of result list.

     public List<Integer> rightSideView(TreeNode root) {
            List<Integer> ans = new ArrayList<Integer>();
            if (root == null) {
                return ans;
            }
            helper(root, ans, 0);
            return ans;
           
        }
        private void helper(TreeNode root, List<Integer> ans, int size) {
            if (root == null) {
                return;
            }
            if (size == ans.size()) {
                ans.add(root.val);
            }
            helper(root.right, ans, size + 1);
            helper(root.left, ans, size + 1);
        }
       
    

    是递的时候操作题意还是归的时候操作? --->尾递归? 输入值? 还是分治? , 辅助全局变量?

  • 相关阅读:
    LintCode "Maximum Gap"
    LintCode "Wood Cut"
    LintCode "Expression Evaluation"
    LintCode "Find Peak Element II"
    LintCode "Remove Node in Binary Search Tree"
    LintCode "Delete Digits"
    LintCode "Binary Representation"
    LeetCode "Game of Life"
    LintCode "Coins in a Line"
    LintCode "Word Break"
  • 原文地址:https://www.cnblogs.com/apanda009/p/7265852.html
Copyright © 2020-2023  润新知