1.根据二叉树创建字符串
题目链接:. - 力扣(LeetCode)
class Solution {
public String tree2str(TreeNode root) {
if(root==null){
return null;
}
StringBuilder stringBuilder=new StringBuilder();
tree2strChild(root,stringBuilder);
return stringBuilder.toString();
}
public void tree2strChild(TreeNode t,StringBuilder stringBuilder){
if(t==null){
return;
}
stringBuilder.append(t.val);
if(t.left!=null){
stringBuilder.append("(");
tree2strChild(t.left,stringBuilder);
stringBuilder.append(")");
}else{
if(t.right==null){
return;
}else{
stringBuilder.append("()");
}
}
if(t.right!=null){
stringBuilder.append("(");
tree2strChild(t.right,stringBuilder);
stringBuilder.append(")");
}else{
return;
}
}
}
2.二叉树前序非递归遍历实现
题目链接:. - 力扣(LeetCode)
public void preOrderTree(TreeNode root){
Stack<TreeNode> stack=new Stack<>();
if(root==null){
return ;
}
TreeNode cur=root;
while (cur!=null || !stack.isEmpty()){
while (cur!=null){
stack.push(cur);
System.out.println(cur.val+" ");
cur=cur.left;
}
TreeNode top=stack.pop();
cur=cur.right;
}
}
3.二叉树中序非递归遍历实现
题目链接:. - 力扣(LeetCode)
public void inOrderTree(TreeNode root){
Stack<TreeNode> stack=new Stack<>();
if(root==null){
return ;
}
TreeNode cur=root;
while (cur!=null || !stack.isEmpty()){
while (cur!=null){
stack.push(cur);
cur=cur.left;
}
TreeNode top=stack.pop();
System.out.println(top.val+" ");
cur=cur.right;
}
}
4.二叉树后序非递归遍历实现
题目链接:. - 力扣(LeetCode)
public void postOrderTree(TreeNode root){
Stack<TreeNode> stack=new Stack<>();
if(root==null){
return ;
}
TreeNode cur=root;
TreeNode prev=null;
while (cur!=null || !stack.isEmpty()){
while (cur!=null){
stack.push(cur);
cur=cur.left;
}
TreeNode top=stack.peek();
if(top.right==null || top.right==prev){
System.out.println(top.val+" ");
stack.pop();
prev=top;
}else {
top=top.right;
}
}
}
希望能对大家有所帮助!!!!