题目:Binary Tree Level Order Traversal II - LeetCode 反转一下最终的顺序就好 代码: class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def levelOrderBottom(self, root: TreeNode) -> List[List[int]]...
代码如下: publicList<Integer>rightSideView(TreeNoderoot){LinkedList<Integer>result=newLinkedList<>();if(Objects.isNull(root)){returnresult;}LinkedList<TreeNode>levelA=newLinkedList<>(),levelB=newLinkedList<>();levelA.addFirst(root);while(!levelA.isEmpty()){TreeNodetreeNode=levelA.removeLast()...
** Inorder Traversal: left -> root -> right ** Preoder Traversal: root -> left -> right ** Postoder Traveral: left -> right -> root 记忆方式:order的名字指的是root在什么位置。left,right的相对位置是固定的。 图片来源:https://leetcode.com/articles/binary-tree-right-side-view/ 对于时...
其实题目的意思就是相当于二叉树每一行的最右边的一个元素,那么简单,先bfs后取每一个数组的最后一位数就可以了,代码如下: 1/**2* Definition for a binary tree node.3* struct TreeNode {4* int val;5* TreeNode *left;6* TreeNode *right;7* TreeNode(int x) : val(x), left(NULL), right(NU...
1、题目描述 2、问题分析 使用层序遍历 3、代码 1vector<int>v;2vector<int> rightSideView(TreeNode*root) {3if(root ==NULL)4returnv;56queue<TreeNode*>q;7q.push(root);89while(!q.empty()) {10intsize =q.size();11for(inti =0; i < size; i++) {12TreeNode *node =q.front();13...
private void dfs(int depth,TreeNode root,List<Integer> ans){ if(depth>maxDepth){ maxDepth=depth; ans.add(root.val); } if(root.right!=null)dfs(depth+1,root.right,ans); if(root.left!=null)dfs(depth+1,root.left,ans); } }
参考LeetCode #102 Binary Tree Level Order Traversal 二叉树的层序遍历 层次遍历按层输出最右边的结点 时间复杂度O(n), 空间复杂度O(n) 代码: C++: /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; ...
private void helper(TreeNode root, int depth){ if(depth>maxdepth){ maxdepth = depth; res.add(root.val); } if(root.right!=null) helper(root.right, depth+1); if(root.left!=null) helper(root.left, depth+1); } } 层序遍历 Level Order Traversal ...
199 Binary Tree Right Side Viewhttps://leetcode-cn.com/problems/binary-tree-right-side-view/ Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom. Example: Input: [1,2,3,null,5,null,4] Output...
199. Binary Tree Right Side View(二叉树的右视图) 题目描述 题目链接 https://leetcode.com/problems/binary-tree-right-side-view/ 方法思路 Apprach1: 基于层序遍历,只添加每层的最后一个节点的值。 Apprach2: The core idea of this algorithm: 1.Each depth of the tree only select one node. 2....