首页 > 其他 > 详细

LeetCode 199. 二叉树的右视图

时间:2020-04-22 21:56:46      阅读:63      评论:0      收藏:0      [点我收藏+]

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

示例:

输入: [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 }

 

LeetCode 199. 二叉树的右视图

原文:https://www.cnblogs.com/woju/p/12755888.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!