博客
关于我
leetcode---987. 二叉树的垂序遍历
阅读量:187 次
发布时间:2019-02-28

本文共 1326 字,大约阅读时间需要 4 分钟。

给定二叉树,按垂序遍历返回其结点值。

对位于 (X, Y) 的每个结点而言,其左右子结点分别位于 (X-1, Y-1) 和 (X+1, Y-1)

把一条垂线从 X = -infinity 移动到 X = +infinity ,每当该垂线与结点接触时,我们按从上到下的顺序报告结点的值( Y 坐标递减)。

如果两个结点位置相同,则首先报告的结点值较小。

按 X 坐标顺序返回非空报告的列表。每个报告都有一个结点值列表。

 

示例 1:

输入:[3,9,20,null,null,15,7]输出:[[9],[3,15],[20],[7]]解释: 在不丧失其普遍性的情况下,我们可以假设根结点位于 (0, 0):然后,值为 9 的结点出现在 (-1, -1);值为 3 和 15 的两个结点分别出现在 (0, 0) 和 (0, -2);值为 20 的结点出现在 (1, -1);值为 7 的结点出现在 (2, -2)。

示例 2:

输入:[1,2,3,4,5,6,7]输出:[[4],[2],[1,5,6],[3],[7]]解释:根据给定的方案,值为 5 和 6 的两个结点出现在同一位置。然而,在报告 "[1,5,6]" 中,结点值 5 排在前面,因为 5 小于 6。
/** * Definition for a binary tree node. * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {	public:		struct node {			int x,y,val;		};		vector
vn; static bool cmp(node & a1,node & a2) { if(a1.x!=a2.x) return a1.x
a2.y; else return a1.val
> verticalTraversal(TreeNode* root) { dfs(0,0,root); vector
> res; sort(vn.begin(),vn.end(),cmp); if(vn.size()>0) { int t=vn[0].x; vector
tmp; tmp.push_back(vn[0].val); for(int i=1; i
val; vn.push_back(t); if(root->left!=NULL) { dfs(x-1,y-1,root->left); } if(root->right!=NULL) { dfs(x+1,y-1,root->right); } } }};

 

转载地址:http://lxki.baihongyu.com/

你可能感兴趣的文章
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>
No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
查看>>
No module named 'crispy_forms'等使用pycharm开发
查看>>
No module named 'pandads'
查看>>
No module named cv2
查看>>
No module named tensorboard.main在安装tensorboardX的时候遇到的问题
查看>>
No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
查看>>
No new migrations found. Your system is up-to-date.
查看>>
No qualifying bean of type XXX found for dependency XXX.
查看>>
No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
查看>>
No resource identifier found for attribute 'srcCompat' in package的解决办法
查看>>