给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。
示例:
输入: [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 }
原文:https://www.cnblogs.com/woju/p/12755888.html