zoukankan      html  css  js  c++  java
  • LeetCode 199. 二叉树的右视图

    给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。

    示例:

    输入: [1,2,3,null,5,null,4]
    输出: [1, 3, 4]
    解释:
    
       1            <---
     /   
    2     3         <---
          
      5     4       <---
    思路:创建一个数组,用来存放二叉树的右视图,利用先序遍历,将树中的结点记录,并不断更新,到最后整颗树遍历结束后,得到的数组便是我们要的二叉树的右视图。
     1 /**
     2  * Definition for a binary tree node.
     3  * struct TreeNode {
     4  *     int val;
     5  *     struct TreeNode *left;
     6  *     struct TreeNode *right;
     7  * };
     8  */
     9 
    10 
    11 /**
    12  * Note: The returned array must be malloced, assume caller calls free().
    13  */
    14 
    15  void pre(struct TreeNode* root, int* returnSize,int depth,int* result)
    16  {
    17      if(root==NULL){
    18          return ;
    19      }
    20      if(depth+1>*returnSize){
    21          *returnSize=depth+1;
    22      }
    23      result[depth]=root->val;
    24      pre(root->left,returnSize,depth+1,result);
    25      pre(root->right,returnSize,depth+1,result);
    26  }
    27 int* rightSideView(struct TreeNode* root, int* returnSize){
    28     *returnSize=0;
    29     int* result;
    30     result=(int*)malloc(1000*sizeof(int));
    31     pre(root,returnSize,0,result);
    32     return result;
    33 }
  • 相关阅读:
    Kafka发送和接收消息
    Kafka主题topic的增删改查
    Kafka启动
    synchronize底层实现原理
    StringBuffer和StringBuilder的区别
    常见的排序算法
    Redis缓存穿透,缓存击穿,缓存雪崩原理及解决方案
    Redis持久化策略
    redis支持的数据类型
    Bytes 类型
  • 原文地址:https://www.cnblogs.com/woju/p/12755888.html
Copyright © 2011-2022 走看看