Leetcode 257: Binary Tree Paths
Posted Keep walking
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 257: Binary Tree Paths相关的知识,希望对你有一定的参考价值。
Given a binary tree, return all root-to-leaf paths.
For example, given the following binary tree:
1 / 2 3 5
All root-to-leaf paths are:
["1->2->5", "1->3"]
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * public int val; 5 * public TreeNode left; 6 * public TreeNode right; 7 * public TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 // define a new node structure to track path, very useful 12 public class TNode 13 { 14 public TreeNode n; 15 public string path; 16 public TNode(TreeNode node, string p) 17 { 18 n = node; 19 path =p; 20 } 21 } 22 23 public IList<string> BinaryTreePaths(TreeNode root) { 24 var result = new List<string>(); 25 if (root == null) return result; 26 27 var stack = new Stack<TNode>(); 28 stack.Push(new TNode(root, root.val.ToString() + "->")); 29 30 while (stack.Count > 0) 31 { 32 var n = stack.Pop(); 33 34 if (n.n.left == null && n.n.right == null) 35 { 36 result.Add(n.path.Substring(0, n.path.Length - 2)); 37 } 38 39 if (n.n.left != null) 40 { 41 stack.Push(new TNode(n.n.left, n.path + n.n.left.val.ToString() + "->")); 42 } 43 44 if (n.n.right != null) 45 { 46 stack.Push(new TNode(n.n.right, n.path + n.n.right.val.ToString() + "->")); 47 } 48 } 49 50 return result; 51 } 52 } 53 54 public class Solution1 { 55 public IList<string> BinaryTreePaths(TreeNode root) { 56 var result = new List<string>(); 57 DFS(root, new List<string>(), result); 58 return result; 59 } 60 61 // if we use IList<string> as path, we need to do backtracking 62 // we can use string directly to avoid doing backtracking 63 private void DFS(TreeNode node, IList<string> path, IList<string> result) 64 { 65 if (node == null) 66 { 67 return; 68 } 69 70 if (node.left == null && node.right == null) 71 { 72 var sb = new StringBuilder(); 73 74 for (int i = 0; i < path.Count; i++) 75 { 76 sb.Append(path[i]); 77 sb.Append("->"); 78 } 79 80 sb.Append(node.val.ToString()); 81 82 result.Add(sb.ToString()); 83 return; 84 } 85 86 path.Add(node.val.ToString()); 87 88 DFS(node.left, path, result); 89 90 DFS(node.right, path, result); 91 92 path.RemoveAt(path.Count - 1); 93 } 94 }
以上是关于Leetcode 257: Binary Tree Paths的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 257. Binary Tree Paths
Java [Leetcode 257]Binary Tree Paths
leetcode?python 257. Binary Tree Paths
leetcode 257. Binary Tree Paths