题目链接:
力扣https://leetcode-cn.com/problems/construct-string-from-binary-tree/
【递归】分三种情况,如果是null直接返回,如果是叶子返回值,如果没有右儿子只遍历左儿子。
class Solution {
public String tree2str(TreeNode root) {
if(root == null) return "";
if(root.right == null && root.left == null) return "" + root.val;
String str = "";
str += root.val;
String left = "";
if(root.right == null)
return str + "(" + tree2str(root.left) + ")";
return str + "(" + tree2str(root.left) + ")" + "(" + tree2str(root.right) + ")";
}
}
【迭代】用栈来模拟先序遍历,先序遍历为根左右,所以这里栈的操作为:根入——根出——右节点入——左节点入——左节点(新根)出····,再用一个哈希表记录当前根是否已经访问完,访问完再补),另外需要注意把根节点排除在外。
class Solution {
public String tree2str(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
stack.add(root);
TreeNode node;
StringBuilder sb = new StringBuilder();
Set<TreeNode> set = new HashSet<>();
while(!stack.empty()){
node = stack.pop();
if(set.contains(node)) {
if(node != root) sb.append(")");
}
else{
set.add(node);
stack.push(node);
if(node != root) sb.append("(");
sb.append(String.valueOf(node.val));
if(node.left == null && node.right != null) sb.append("()");
if(node.right != null) stack.push(node.right);
if(node.left != null) stack.push(node.left);
}
}
return sb.toString();
}
}