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 }
  • 相关阅读:
    行为型模式之 命令模式
    结构型模式之 代理模式
    oop编程思想
    2013应届毕业生各大IT公司待遇整理汇总篇(转)
    python定义class
    python——博客园首页信息提取与分析(转载有改动)
    深入浅出TCP/IP协议
    python基础之socket
    python基础
    c++stl之stack
  • 原文地址:https://www.cnblogs.com/woju/p/12755888.html
Copyright © 2011-2022 走看看