数据结构—基本树的操作小结

来源:互联网 发布:大数据时代 全本下载 编辑:程序博客网 时间:2024/05/22 02:24

整理几个树的算法。

1树的复制:每次递归创建一个节点,此节点的左右孩子递归创建。

public static Tree duplicate(Tree root){    Tree newRoot = new Tree(root.val);    if (root.left!=null)        newRoot.left=duplicate(root.left);    if (root.right!=null)        newRoot.right=duplicate(root.right);    return newRoot;}

2树的节点数:左右子树的节点个树+1

public static int Size(Tree root){    if (root==null)return 0;//节点高度看作1    return 1+Size(root.left)+Size(root.right);}

3树的深度:左右子树中最深的那个+1是自身的深度

public static int Depth(Tree root){    if (root==null)return 0;    return 1+Math.max(Depth(root.left),Depth(root.right));}

4树的非递归后序遍历:后续遍历先遍历左孩子,然后遍历有孩子,最后遍历自身。递归算法都会考虑到用栈来解决。因此当要访问此节点时要看一下这个节点的右孩子是否为空,或者右孩子被访问过了。如果这个节点还有右孩子的话,将右孩子的所有左孩子压入栈中(当前右孩子的也要如栈)

public static void PostOrder(Tree root){    Stack<Tree> stack = new Stack<Tree>();    stack.push(root);    Tree lastVist = null;    while (!stack.isEmpty()){        Tree cur = stack.pop();        if(cur.right==null||cur.right==lastVist){            System.out.print(cur.val);            lastVist=cur;        }else{            stack.push(cur);            cur=cur.right;            while (cur!=null){                stack.push(cur);                cur=cur.left;            }        }    }}

5树的非递归中序遍历:中序遍历while的终止条件发生变化,主要原因在于中序遍历先打印根,再打印右孩子,打印完根的时候,栈就空了,后续遍历最后打印根,因此后续遍历的循环截止条件可以直接判断是否为空即可。

public static void inOrder(Tree root){    Tree cur = root;    Stack<Tree> stack = new Stack<>();    while (!stack.isEmpty()||cur!=null){        while (cur!=null){            stack.push(cur);            cur=cur.left;        }        if (!stack.isEmpty()){            cur=stack.pop();            System.out.println(cur.val);            cur=cur.right;        }    }}

6树的非递归前序遍历:树的前序遍历和中序遍历非常相似,唯一不同的地方就是打印的为止放在了入栈的位置,而不是出栈的位置。

public static void preOrder(Tree root){    Tree cur = root;    Stack<Tree> stack = new Stack<>();    while (!stack.isEmpty()||cur!=null){        while (cur!=null){            System.out.println(cur.val);            stack.push(cur);            cur=cur.left;        }        if (!stack.isEmpty()){            cur=stack.pop();            cur=cur.right;        }    }}

7树的非递归层序遍历:层序遍历使用队列就可以解决

public static void layerOrder(Tree root){    Queue<Tree> queue = new LinkedList<Tree>();    queue.offer(root);    while (!queue.isEmpty()){        Tree cur = queue.poll();        System.out.println(cur.val);        if (cur.left!=null)        queue.offer(cur.left);        if (cur.right!=null)        queue.offer(cur.right);    }}


原创粉丝点击