Leetcode---每个节点的右向指针--递归解法(两种)

本文接上一篇文章:非递归方法

解法一:

  • 先将根节点的next置为null,再分别处理左右孩子
  • 左右孩子采用递归的方式
  • 这里的递归不是最优的,递归过程中产生了重复,而必须这样写目的是处理left->right和right->left,经过分析,除最外侧的节点之外,均产生了重复的递归
	public void connect(TreeLinkNode root) {
		//递归算法连接右向指针
		if(root==null) {
			return;
		}
		root.next = null;
		connect(root.left,root.right);
	}
	public void connect(TreeLinkNode left,TreeLinkNode right) {
		if(left==null&&right==null) {
			return;
		}
		//连接左右孩子节点
		if(left!=null&&right!=null) {
			left.next = right;
			right.next = null;		//先置为null
			connect(left.left,left.right);
			connect(left.right, right.left);
			connect(right.left, right.right);
		}
	}

解法二:

  • 处理上面重复递归的问题,left->right和right->left是否需要处理就看left->next是否为null,不为null,就需要连接
public void connect(TreeLinkNode root) {
		if(root==null) {
			return;
		}
		if(root.left!=null) {
			root.left.next = root.right;
			root.right.next = root.next==null?null:root.next.left;
		}
		connect(root.left);
		connect(root.right);
	}

猜你喜欢

转载自blog.csdn.net/tiaochewang219/article/details/84648524