二叉树常见遍历方式与题目总结

二叉树常见遍历方式与题目总结

二叉树常见遍历方式

树的定义

/**

\* Definition for a binary tree node.

\* public class TreeNode {

\* int val;

\* TreeNode left;

\* TreeNode right;

\* TreeNode(int x) { val = x; }

\* }

*/

(1)前序遍历

先访问根节点,然后前序遍历左子树,再前序遍历右子树

(a) 递归的方法遍历


void preoder(TreeNode T)

{

        if(T==null) return ;

        sysytem.out。print(T.val);

        preoder(TreeNode T.left);

        preoder(TreeNode T.right);

}



(b)非递归


class Solution {
  public List<Integer> preorderTraversal(TreeNode root) {
    LinkedList<TreeNode> stack = new LinkedList<>();
    LinkedList<Integer> output = new LinkedList<>();
    if (root == null) {
      return output;
    }

    stack.add(root);
    while (!stack.isEmpty()) {
      TreeNode node = stack.pollLast();
      output.add(node.val);
      if (node.right != null) {
        stack.add(node.right);
      }
      if (node.left != null) {
        stack.add(node.left);
      }
    }
    return output;
  }
}

(2)中序遍历

(a)递归

void preoder(TreeNode T)

{

    if(T==null) return ;
    preoder(TreeNode T.left);

    sysytem.out.print(T.val);


    preoder(TreeNode T.right);


}

(b) 非递归

public void inOrder() {
		Node current = root;
		//把LinkedList作为栈使用
		LinkedList<Node> s = new LinkedList<Node>();
		while (current != null || !s.isEmpty()) {
			while (current != null) {
				s.addFirst(current);
				current = current.left;
			}
			if (!s.isEmpty()) {
				current = s.removeFirst();
				System.out.print(current.data + " -> ");
				current = current.right;
			}
		}
	}

(3)后序遍历

(a) 递归

public static void postOrderRecur(TreeNode head) {
    if (head == null) {
        return;
    }
    postOrderRecur(head.left);
    postOrderRecur(head.right);
    System.out.print(head.value + " ");
}

(b)非递归

public static void postOrderIteration(TreeNode head) {
		if (head == null) {
			return;
		}
		Stack<TreeNode> stack1 = new Stack<>();
		Stack<TreeNode> stack2 = new Stack<>();
		stack1.push(head);
		while (!stack1.isEmpty()) {
			TreeNode node = stack1.pop();
			stack2.push(node);
			if (node.left != null) {
				stack1.push(node.left);
			}
			if (node.right != null) {
				stack1.push(node.right);
			}
		}
		while (!stack2.isEmpty()) {
			System.out.print(stack2.pop().value + " ");
		}
	}

	if (node.right != null) {
				stack1.push(node.right);
			}
		}
		while (!stack2.isEmpty()) {
			System.out.print(stack2.pop().value + " ");
		}
	}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值