LC_606
作者:互联网
今天是一道先序遍历二叉树的题目
先看题目
递归的思路比较简单,先考虑使用递归的方法解题
方法1:递归
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode() {} 8 * TreeNode(int val) { this.val = val; } 9 * TreeNode(int val, TreeNode left, TreeNode right) { 10 * this.val = val; 11 * this.left = left; 12 * this.right = right; 13 * } 14 * } 15 */ 16 class Solution { 17 public String ret = ""; 18 public String tree2str(TreeNode root) { 19 pre(root); 20 return ret.substring(0,ret.length() - 1); 21 } 22 public void pre(TreeNode root){ 23 if(root != null){ 24 ret += String.valueOf(root.val); 25 } 26 27 if(root.left != null){ 28 ret += "("; 29 pre(root.left); 30 }else if(root.right != null){ 31 ret += "()"; 32 } 33 if(root.right != null){ 34 ret += "("; 35 pre(root.right); 36 } 37 ret += ")"; 38 } 39 }
方法2 迭代模拟递归
标签:606,TreeNode,LC,val,ret,right,root,left 来源: https://www.cnblogs.com/yu-xia-zheng-ye/p/16025442.html