binaryTreePath(results,newArrayList<Integer>(), root);returnresults; }publicvoidbinaryTreePath(List<String> results, List<Integer>path, TreeNode cur) {if(cur ==null) {return;//root==null}if(cur.left ==null&& cur.right ==null) {//需要在上层判断 path.add(cur.val);//add cur's valStr...
排名第一的top solution是从上往下的原则,每一次把当前的path传给递归的function,这样到叶子就截止了,funcition的返回值是void的。以后遇到问题可以从上往下,从下往上都想想,参数的个数也可以多加几个,不要局限于一种思路出不来。 从上往下: publicclassSolution {publicList<String>binaryTreePaths(TreeNode root)...
* type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ func binaryTreePaths(root *TreeNode) []string { var res []string if root == nil { return res } dfs(root, "", &res) return res } func dfs(root *TreeNode, path string, res *[]string) { if r...
def maxPathSum(self, root): """ :type root: TreeNode :rtype: int """ self.maxSum = float('-inf') self._maxPathSum(root) return self.maxSum def _maxPathSum(self, root): # DFS if root is None: return 0 left = self._maxPathSum(root.left) right = self._maxPathSum(root.r...
13 void DFS(string path,TreeNode* t) 14 { 15 if(t->left==NULL&&t->right==NULL) 16 { 17 ans.push_back(path); 18 return ; 19 } 20 21 if(t->left) 22 DFS(path+"->"+to_string(t->left->val),t->left); 23 if(t->right) ...
LeetCode 226 Invert Binary Tree 层序遍历方法 package com.example.demo; import java.util.LinkedList; import java.util.Queue; /** * Created By poplar on 2019/10/30 */ public class InvertBinaryTree { public static void main(String[] args) { TreeNode node = new TreeNode(1); TreeNode node...
Can you solve this real interview question? Lowest Common Ancestor of a Binary Tree - Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree. According to the definition of LCA on Wikipedia [https://en.wikipedia.org/wi
LeetCode 536. Construct Binary Tree from String You need to construct a binary tree from a string consisting of parenthesis and integers. The whole input represents a binary tree. It contains an integer followed by zero, one or two pairs of parenthesis. The integer represents the root's value...
简单 95. 不同的二叉搜索树 II 74.6% 中等 96. 不同的二叉搜索树 71.5% 中等 98. 验证二叉搜索树 39.3% 中等 99. 恢复二叉搜索树 61.3% 中等 100. 相同的树 63.2% 简单 101. 对称二叉树 62.3% 简单 102. 二叉树的层序遍历 69.7% 中等 103. 二叉树的锯齿形层序遍历 60.2% 中等 104. 二叉树的最大...
145. 二叉树的后序遍历 - 给你一棵二叉树的根节点 root ,返回其节点值的 后序遍历 。 示例 1: 输入:root = [1,null,2,3] 输出:[3,2,1] 解释: [https://assets.leetcode.com/uploads/2024/08/29/screenshot-2024-08-29-202743.png] 示例 2: 输入:root =